POJ-3264:Balanced Lineup

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/wingrez/article/details/81947253

POJ-3264:Balanced Lineup

来源:POJ

标签:数据结构,RMQ问题

参考资料:

相似题目:

题目

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.

输入

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.

输出

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.

输入样例

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

输出样例

6
3
0

题目大意

解题思路

参考代码

#include<stdio.h>
#include<vector>
#include<algorithm>
#define MAXN 50005
using namespace std;

int minnum[MAXN][20];
int maxnum[MAXN][20];

int N,Q;
int arr[MAXN];

void RMQ_init(){
    for(int i=0; i<N; i++){
        minnum[i][0]=arr[i];
        maxnum[i][0]=arr[i];
    }
    for(int j=1; (1<<j)<=N; j++){
        for(int i=0; i+(1<<j)-1<N; i++){
            minnum[i][j]=min(minnum[i][j-1], minnum[i+(1<<(j-1))][j-1]);
            maxnum[i][j]=max(maxnum[i][j-1], maxnum[i+(1<<(j-1))][j-1]);
        }
    }
}

void RMQ(int L,int R, int& minn, int& maxn){
    int k=0;
    while((1<<(k+1)) <= R-L+1){
        k++;
    }
    minn=min(minnum[L][k], minnum[R-(1<<k)+1][k]);
    maxn=max(maxnum[L][k], maxnum[R-(1<<k)+1][k]);
}

int main(){
    while(~scanf("%d%d",&N,&Q)){
        for(int i=0;i<N;i++){
            scanf("%d",&arr[i]);
        }
        RMQ_init();
        int l,r;
        int minn,maxn;
        for(int i=0;i<Q;i++){
            scanf("%d%d",&l,&r);
            RMQ(l-1,r-1,minn,maxn);
            printf("%d\n",maxn-minn);
        }
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/wingrez/article/details/81947253