# poj 3264 Balanced Lineup

Balanced Lineup
Time Limit: 5000MS Memory Limit: 65536KTotal Submissions: 33375 Accepted: 15659Case 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 31734251 54 62 2`

Sample Output

`630`

`<span style="font-size:18px;">#include<algorithm>#include<iostream>#include<cstdio>#include<cstring>using namespace std;const int INF = 10000000;int minV = INF;int maxV = -INF;struct node{int L, R;int minV, maxV;int Mid(){return(L + R) / 2;}};node tree[801000];void build(int root, int L, int R) ///先建一颗空树{tree[root].L = L;tree[root].R = R;tree[root].minV = INF;tree[root].maxV = -INF;if(L == R) return;build(root * 2 + 1 , L , (L + R) / 2);build(root * 2 + 2 , (L + R) / 2 + 1 , R);}void Insert(int root, int i, int v) ///插入操作，将具体每个数插入树中{if(tree[root].L == tree[root].R){tree[root].maxV = v;tree[root].minV = v;return ;}tree[root].minV = min(tree[root].minV , v);tree[root].maxV = max(tree[root].maxV , v);if(i <= tree[root].Mid()){Insert(root * 2 + 1 , i , v);}else{Insert(root * 2 + 2 , i , v);}}void Query(int root, int s, int e) {if(tree[root].minV >= minV && tree[root].maxV <= maxV){///printf("minV = %d   maxV = %d", tree[root].minV , tree[root].maxV);return;}if(tree[root].L == s && tree[root].R == e){minV = min(tree[root].minV , minV);maxV = max(tree[root].maxV , maxV);return;}if(e <= tree[root].Mid()){Query(root * 2 + 1 , s , e);}else if(s > tree[root].Mid()){Query(root * 2 + 2 , s , e);}else{Query(root * 2 + 1 , s , tree[root].Mid());Query(root * 2 + 2 , tree[root].Mid() + 1 , e);}}int main(){int t, n, h, s, e;scanf("%d%d", &t, &n);build(0, 1, t);for(int i=1; i<=t; ++i){scanf("%d", &h);Insert(0, i, h);}///printf("\n");///for(int i=0; i<10; ++i)///{///printf("%d   %d\n",tree[i].minV , tree[i].maxV);///}///printf("\n");for(int i=0; i<n; ++i){scanf("%d%d", &s, &e);minV = INF;maxV = -INF;Query(0, s, e);///printf("minV = %d   maxV = %d\n", minV, maxV);printf("%d\n", maxV - minV);}return 0;}</span>`

0 0