POJ 3264 Balanced Lineup

来源:互联网 发布:易语言cc攻击源码 编辑:程序博客网 时间:2024/06/07 12:08
Balanced Lineup
Time Limit: 5000MS Memory Limit: 65536KTotal Submissions: 39766 Accepted: 18664Case 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 andQ.
Lines 2..N+1: Line i+1 contains a single integer that is the height of cowi
Lines N+2..N+Q+1: Two integers A and B (1 ≤ABN), representing the range of cows from A toB 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 31734251 54 62 2

Sample Output

630


RMQ问题,在一个数组的指定区间内找寻最大值和最小值,并输出他们的差。

套了模板过。


#include <stdio.h>#include <algorithm>#define N 50005using namespace std;int dpmin[N][100];int dpmax[N][100];int a[N];int minn,maxn;void RMQ_init(int n){for(int i=1;i<=n;i++) dpmin[i][0]=a[i],dpmax[i][0]=a[i];for(int j=1;(1<<j)<=n;j++)for(int i=1;i+(1<<j)-1<=n;i++)    dpmin[i][j]=min(dpmin[i][j-1],dpmin[i+(1<<(j-1))][j-1]),dpmax[i][j]=max(dpmax[i][j-1],dpmax[i+(1<<(j-1))][j-1]);}void RMQ(int l,int r){int k=0;while(1<<(k+1)<r-l+1) k++;minn=min(dpmin[l][k],dpmin[r-(1<<k)+1][k]),maxn=max(dpmax[l][k],dpmax[r-(1<<k)+1][k]);}int main(){        int n,q;        while(scanf("%d%d",&n,&q)>0)        {                for(int i=1;i<=n;i++)                        scanf("%d",&a[i]);                        RMQ_init(n);                while(q--)                {                        int l,r;                        scanf("%d%d",&l,&r);                        if (l > r) swap(l, r);                        RMQ(l,r);                        printf("%d\n",maxn-minn);                }        }        return 0;}

0 0