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
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
Sample Input
6 3 1 7 3 4 2 5 1 5 4 6 2 2
Sample Output
6 3 0
#include <iostream> #include <cstdio> using namespace std; #define maxn 50008 int key[maxn]; struct ST { int l,r,maxkey,minkey; }st[4*maxn]; inline int max(int a,int b) { return a>b?a:b; } inline int min(int a,int b) { return a>b?b:a; } void buildtree(int id,int l,int r) { st[id].l=l; st[id].r=r; if(l==r) { st[id].maxkey=st[id].minkey=key[l]; return; } int mid=(l+r)/2; buildtree(2*id,l,mid); buildtree(2*id+1,mid+1,r); st[id].maxkey=max(st[2*id].maxkey,st[2*id+1].maxkey); st[id].minkey=min(st[2*id].minkey,st[2*id+1].minkey); } int qmax(int id,int l,int r) { if(st[id].l==l&&st[id].r==r) { return st[id].maxkey; } if(st[2*id].r>=r) { return qmax(2*id,l,r); } if(st[2*id+1].l<=l) { return qmax(2*id+1,l,r); } int max1=qmax(2*id,l,st[2*id].r); int max2=qmax(2*id+1,st[2*id+1].l,r); int maxx=max(max1,max2); return maxx; } int qmin(int id,int l,int r) { if(st[id].l==l&&st[id].r==r) { return st[id].minkey; } if(st[2*id].r>=r) { return qmin(2*id,l,r); } if(st[2*id+1].l<=l) { return qmin(2*id+1,l,r); } int min1=qmin(2*id,l,st[2*id].r); int min2=qmin(2*id+1,st[2*id+1].l,r); int minn=min(min1,min2); return minn; } int main() { int n,q; while(scanf("%d%d",&n,&q)==2) { for(int i=1;i<=n;i++) { scanf("%d",&key[i]); } buildtree(1,1,n);//这好像不是我第一次先建树然后再输入key值了。。。。 for(int i=1;i<=q;i++) { int u,v; scanf("%d%d",&u,&v); printf("%d\n",qmax(1,u,v)-qmin(1,u,v)); } } return 0; }