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
Source
1 #include2 #include 3 #define inf 1000000005 4 #include 5 using namespace std; 6 7 int a[50005]; 8 int mmin,mmax; 9 10 struct Node11 {12 int l,r;13 int min,max;14 }node[200100];15 16 void build(int root,int l,int r)17 {18 node[root].l = l;19 node[root].r = r;20 if(node[root].l==node[root].r)21 {22 node[root].min=a[l];23 node[root].max=a[l];24 return ;25 }26 int mid = (l+r)/2;27 build(root<<1,l,mid);28 build(root<<1|1,mid+1,r);29 node[root].min = min(node[root<<1].min,node[root<<1|1].min);30 node[root].max = max(node[root<<1].max,node[root<<1|1].max);31 }32 void query(int root,int l,int r)33 {34 if(l<=node[root].l && r>=node[root].r)35 {36 mmin = min(mmin,node[root].min);37 mmax = max(mmax,node[root].max);38 return;39 }40 int mid=(node[root].l+node[root].r)/2;41 42 if(r<=mid) query(root<<1,l,r);43 else if(l>=mid+1) query(root<<1|1,l,r);44 else45 {46 query(root<<1,l,mid);47 query(root<<1|1,mid+1,r);48 }49 }50 51 int main()52 {53 int n,q,b,c;54 while(scanf("%d %d",&n,&q)!=EOF)55 {56 for(int i=1; i<=n; i++) scanf("%d",&a[i]);57 build(1,1,n);58 while(q--)59 {60 scanf("%d%d",&b,&c);61 mmin = inf;62 mmax =-inf;63 query(1,b,c);64 printf("%d\n",mmax-mmin);65 }66 }67 68 return 0;69 }