POJ 3264 Balanced Lineup(RMQ)

来源:互联网 发布:安卓锁屏拍照软件 编辑:程序博客网 时间:2024/05/22 17:09

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

大致题意:有n头牛,每头牛有一个价值w,现在有q次查询,每次查询一个区间[l,r],问你该区间内牛的最大价值减去牛的最小价值是多少?

思路:直接套RMQ模板

代码如下

#include<iostream>#include<algorithm>#include<string>#include<cstdio>#include<cstring>#include<queue>#include<vector>#include<cstring>#include <sstream> #include<cmath>#include<map>#define LL long long  #define ULL unsigned long long  using namespace std;const int N=50010;int num,query;int maxn[N][20],minn[N][20];void RMQ(){    for(int j=1;j<20;j++)    for(int i=1;i<=num;i++)    if(i+(1<<j)-1<=num)    {        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 query_max(int l,int r){    int k=log(r-l+1)/log(2);    return max(maxn[l][k],maxn[r-(1<<k)+1][k]);}int query_min(int l,int r){    int k=log(r-l+1)/log(2);    return min(minn[l][k],minn[r-(1<<k)+1][k]);}int main(){    scanf("%d%d",&num,&query);    for(int i=1;i<=num;i++)    {        scanf("%d",&maxn[i][0]);        minn[i][0]=maxn[i][0];    }     RMQ();    while(query--)    {        int l,r;        scanf("%d%d",&l,&r);        printf("%d\n",query_max(l,r)-query_min(l,r));    }    return 0; }
原创粉丝点击