Balanced Lineup
Time Limit: 5000MS | Memory Limit: 65536K | |
Total Submissions: 44121 | Accepted: 20715 | |
Case 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 好久没写,写搓了,orz 代码: #include#include #include #include using namespace std; const int maxn=70000; int a[maxn]; int x,y; struct nod { int mi; int ma; }; nod tree[4*maxn]; void build(int p,int l,int r) { if(l==r) {tree[p].mi=a[l];tree[p].ma=a[l];return;} int mid=(l+r)>>1; build(p<<1,l,mid); build((p<<1)+1,mid+1,r); tree[p].mi=min(tree[p<<1].mi,tree[(p<<1)+1].mi); tree[p].ma=max(tree[p<<1].ma,tree[(p<<1)+1].ma); } int find1(int p,int l,int r,int x,int y) { if(x<=l&&r<=y) {return tree[p].ma;} int mid=(l+r)>>1; if(y<=mid) return find1(p<<1,l,mid,x,y); else if(x>mid) return find1((p<<1)+1,mid+1,r,x,y); else return max(find1(p<<1,l,mid,x,mid),find1((p<<1)+1,mid+1,r,mid+1,y)); } int find2(int p,int l,int r,int x,int y) { if(x<=l&&r<=y) {return tree[p].mi;} int mid=(l+r)>>1; if(y<=mid) return find2(p<<1,l,mid,x,y); else if(x>mid) return find2((p<<1)+1,mid+1,r,x,y); else return min(find2(p<<1,l,mid,x,mid),find2((p<<1)+1,mid+1,r,mid+1,y)); } int main() { int n,q; int x,y; while(scanf("%d%d",&n,&q)!=EOF) { memset(tree,0,sizeof(tree)); for(int i=1;i<=n;i++) scanf("%d",&a[i]); build(1,1,n); while(q--) { scanf("%d%d",&x,&y); printf("%d\n",find1(1,1,n,x,y)-find2(1,1,n,x,y)); } } return 0; }