Balanced Lineup
Time Limit: 5000MS | Memory Limit: 65536K | |
Total Submissions: 47042 | Accepted: 22071 | |
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 3 1 7 3 4 2 5 1 5 4 6 2 2
Sample Output
6 3 0
Source
拿来练手的线段树交的时候还WA了一次……我还是太naive了
1 #include <cstdio> 2 #include <cmath> 3 #include <cstdlib> 4 #include <cstring> 5 #include <queue> 6 #include <stack> 7 #include <vector> 8 #include <iostream> 9 #include "algorithm" 10 using namespace std; 11 typedef long long LL; 12 13 #define lson rt<<1,l,m 14 #define rson rt<<1|1,m+1,r 15 16 const int MAX=50005; 17 int n,q; 18 int Max[MAX<<2],Min[MAX<<2]; 19 20 void PushUp(int rt){ 21 Max[rt]=max(Max[rt<<1],Max[rt<<1|1]); 22 Min[rt]=min(Min[rt<<1],Min[rt<<1|1]); 23 } 24 void build(int rt,int l,int r){ 25 if (l==r) 26 {scanf("%d",&Max[rt]); 27 Min[rt]=Max[rt]; 28 return; 29 } 30 int m=(l+r)>>1; 31 build(lson); 32 build(rson); 33 PushUp(rt); 34 } 35 void search(int x,int y,int rt,int l,int r,int &a1,int &a2){ 36 if (x<=l && r<=y) 37 {a1=max(a1,Max[rt]); 38 a2=min(a2,Min[rt]); 39 return; 40 } 41 int m=(l+r)>>1; 42 if (x<=m) 43 search(x,y,lson,a1,a2); 44 if (m<y) 45 search(x,y,rson,a1,a2); 46 } 47 int main(){ 48 freopen ("balanced.in","r",stdin); 49 freopen ("balanced.out","w",stdout); 50 int i,j; 51 int low,high; 52 int x,y; 53 scanf("%d%d",&n,&q); 54 build(1,1,n); 55 for (i=1;i<=q;i++) 56 {scanf ("%d%d",&low,&high); 57 x=0,y=1000000000; 58 search(low,high,1,1,n,x,y); 59 printf("%d\n",x-y); 60 } 61 return 0; 62 }