Balanced Lineup POJ - 3264
#include<iostream> #include<cstdio> #include<cstring> #include<algorithm> using namespace std; #define MAXN 50010 int n , q; int h[MAXN]; struct Node{ int l; int r; int minNum; int maxNum; } tr[4*MAXN]; void build(int l,int r,int u){ tr[u].l=l; tr[u].r=r; if(l==r) { tr[u].minNum=h[l]; tr[u].maxNum=h[l]; return; } int mid=l+r>>1; build(l ,mid,u<<1); build(mid+1,r,u<<1|1); tr[u].minNum=min(tr[u<<1].minNum,tr[(u<<1)+1].minNum); tr[u].maxNum=max(tr[u<<1].maxNum,tr[(u<<1)+1].maxNum); } //查询最大值 int queryMax(int l,int r,int u){ if(tr[u].l==l&&tr[u].r==r) return tr[u].maxNum; int mid=tr[u].l+tr[u].r>>1; if(r<=mid) return queryMax(l,r,u<<1); else if(l>mid) return queryMax(l,r,u<<1|1); else return max(queryMax(l,mid,u<<1),queryMax(mid+1,r,(u<<1)+1)); } //查询最小值 int queryMin(int l,int r,int u) { if(tr[u].l==l&&tr[u].r==r) return tr[u].minNum; int mid=tr[u].l+tr[u].r>>1; if(r<=mid) return queryMin(l,r,u<<1); else if(l>mid) return queryMin(l ,r,u<<1|1); else return min(queryMin(l,mid,u<<1),queryMin(mid+1,r,(u<<1)+1)); } int main(){ while(scanf("%d%d",&n,&q)!=EOF) { for(int i=1;i<=n;i++) scanf("%d",&h[i]); build(1,n,1); int l,r; for(int i=0;i<q;i++){ scanf("%d%d",&l,&r); cout<<queryMax(l,r,1)-queryMin(l,r,1)<<endl; } } return 0; }