欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Balanced Lineup(poj 3264)

程序员文章站 2022-04-08 09:10:50
...
Time Limit: 5000MS   Memory Limit: 65536K
Total Submissions: 63081   Accepted: 29427
Case Time Limit: 2000MS

Description

For the daily milking, Farmer John's N cows (1 ≤ N ≤ 50,000) always line up in the same order. One day Farmer John decides to organize a game of Ultimate Frisbee with some of the cows. To keep things simple, he will take a contiguous range of cows from the milking lineup to play the game. However, for all the cows to have fun they should not differ too much in height.

Farmer John has made a list of Q (1 ≤ Q ≤ 200,000) potential groups of cows and their heights (1 ≤ height ≤ 1,000,000). For each group, he wants your help to determine the difference in height between the shortest and the tallest cow in the group.

Input

Line 1: Two space-separated integers, N and Q
Lines 2..N+1: Line i+1 contains a single integer that is the height of cow i 
Lines N+2..N+Q+1: Two integers A and B (1 ≤ A ≤ B ≤ N), representing the range of cows from A to B inclusive.

Output

Lines 1..Q: Each line contains a single integer that is a response to a reply and indicates the difference in height between the tallest and shortest cow in the range.

Sample Input

6 3
1
7
3
4
2
5
1 5
4 6
2 2

Sample Output

6
3
0

Source

USACO 2007 January Silver

RMQ算法,参考博客:https://blog.csdn.net/niushuai666/article/details/6624672

https://blog.csdn.net/enjoy_pascal/article/details/78301708

 

设f[i,j]f[i,j]表示[i,i+2j−1][i,i+2j−1]区间里的最大值 
明显地,初始化f[i,0]=a[i]f[i,0]=a[i],因为[i,i+20]=[i][i,i+20]=[i] 
DP方程即为f[i,j]=max(f[i,j−1],f[i+2j−1,j−1])

Balanced Lineup(poj 3264)

#include<bits/stdc++.h>
using namespace std;
const int MAX=50005;
int maxn[MAX][20],minn[MAX][20],n,q;
void RMQ()
{
    for(int j=1;(1<<j)<=n;j++)
    {
        for(int i=1;i+(1<<j)-1<=n;i++)
        {
            maxn[i][j]=max(maxn[i][j-1],maxn[i+(1<<(j-1))][j-1]);
            minn[i][j]=min(minn[i][j-1],minn[i+(1<<(j-1))][j-1]);
        }
    }
}
int main()
{
    scanf("%d%d",&n,&q);
    int a;
    for(int i=1;i<=n;i++)
    {
        scanf("%d",&a);
        maxn[i][0]=minn[i][0]=a;
    }
    RMQ();
    int L,R;
    for(int i=1;i<=q;i++)
    {
        scanf("%d%d",&L,&R);
        int k=0;
        while((1<<(k+1))<R-L+1) k++;//int k=log(double(R-L+1))/log(2.0);
        printf("%d\n",max(maxn[L][k],maxn[R-(1<<k)+1][k])-min(minn[L][k],minn[R-(1<<k)+1][k]));
    }
    return 0;
}
相关标签: RMQ算法