【线段树查询区间最值】poj 3264 Balanced Lineup
1 #include<cstdio> 2 #include<algorithm> 3 using namespace std; 4 5 const int maxn=50005; 6 struct Seg 7 { 8 int l,r,mi,ma; 9 }tree[maxn*4]; 10 int val[maxn]; 11 12 void build(int l,int r,int i=1) 13 { 14 tree[i].l=l; 15 tree[i].r=r; 16 if (l==r) 17 { 18 tree[i].mi=val[l]; 19 tree[i].ma=val[l]; 20 } 21 else 22 { 23 int mid=l+r>>1; 24 build(l,mid,i<<1); 25 build(mid+1,r,i<<1|1); 26 tree[i].mi=min(tree[i<<1].mi,tree[i<<1|1].mi); 27 tree[i].ma=max(tree[i<<1].ma,tree[i<<1|1].ma); 28 } 29 } 30 31 int querymi(int l,int r,int i=1) 32 { 33 if (tree[i].l==l && tree[i].r==r) return tree[i].mi; 34 int mid=tree[i].l+tree[i].r>>1; 35 if (r<=mid) return querymi(l,r,i<<1); 36 if (l>mid) return querymi(l,r,i<<1|1); 37 return min(querymi(l,mid,i<<1),querymi(mid+1,r,i<<1|1)); 38 } 39 40 int queryma(int l,int r,int i=1) 41 { 42 if (tree[i].l==l && tree[i].r==r) return tree[i].ma; 43 int mid=tree[i].l+tree[i].r>>1; 44 if (r<=mid) return queryma(l,r,i<<1); 45 if (l>mid) return queryma(l,r,i<<1|1); 46 return max(queryma(l,mid,i<<1),queryma(mid+1,r,i<<1|1)); 47 } 48 49 int main() 50 { 51 int n,m; 52 scanf("%d%d",&n,&m); 53 for (int i=1;i<=n;i++) scanf("%d",&val[i]); 54 build(1,n); 55 for (int i=0;i<m;i++) 56 { 57 int l,r; 58 scanf("%d%d",&l,&r); 59 printf("%d\n",queryma(l,r)-querymi(l,r)); 60 } 61 return 0; 62 }