1 #include<cstdio> 2 #define MAXN 50010 3 #define INF 987654321 4 int a[MAXN<<2],b[MAXN<<2]; 5 inline int MAX(int x,int y) 6 { 7 return x>y?x:y; 8 } 9 inline int MIN(int x,int y) 10 { 11 return x>y?y:x; 12 } 13 inline void PushUp(int rt) 14 { 15 a[rt]=MAX(a[rt<<1],a[rt<<1|1]); 16 b[rt]=MIN(b[rt<<1],b[rt<<1|1]); 17 } 18 void Build(int L,int R,int rt) 19 { 20 if(L==R) 21 { 22 scanf("%d",&a[rt]); 23 b[rt]=a[rt]; 24 } 25 else 26 { 27 int mid=(L+R)>>1; 28 Build(L,mid,rt<<1); 29 Build(mid+1,R,rt<<1|1); 30 PushUp(rt); 31 } 32 } 33 int Big(int x,int y,int L,int R,int rt) 34 { 35 if(x<=L&&R<=y) 36 return a[rt]; 37 int mid,ans; 38 mid=(L+R)>>1; 39 ans=-INF; 40 if(mid>=x) 41 ans=MAX(ans,Big(x,y,L,mid,rt<<1)); 42 if(y>mid) 43 ans=MAX(ans,Big(x,y,mid+1,R,rt<<1|1)); 44 return ans; 45 } 46 int Small(int x,int y,int L,int R,int rt) 47 { 48 if(x<=L&&R<=y) 49 return b[rt]; 50 int mid,ans; 51 mid=(L+R)>>1; 52 ans=INF; 53 if(mid>=x) 54 ans=MIN(ans,Small(x,y,L,mid,rt<<1)); 55 if(y>mid) 56 ans=MIN(ans,Small(x,y,mid+1,R,rt<<1|1)); 57 return ans; 58 } 59 int main() 60 { 61 int n,q,x,y; 62 while(~scanf("%d%d",&n,&q)) 63 { 64 Build(1,n,1); 65 while(q--) 66 { 67 scanf("%d%d",&x,&y); 68 printf("%d\n",Big(x,y,1,n,1)-Small(x,y,1,n,1)); 69 } 70 } 71 return 0; 72 }
转载于:https://www.cnblogs.com/DrunBee/archive/2012/05/21/2511820.html