【BZOJ】1699 [Usaco2007 Jan]Balanced Lineup排队
【算法】线段树
#include<cstdio> #include<cctype> #include<algorithm> using namespace std; const int inf=0x3f3f3f3f,maxn=50010; struct tree{int l,r,mins,maxs;}t[maxn*3]; int n,q,a[maxn]; int read_t;char c; int read() { read_t=0; while(!isdigit(c=getchar())); do{read_t=read_t*10+c-'0';}while(isdigit(c=getchar())); return read_t; } void build(int k,int l,int r) { t[k].l=l;t[k].r=r; if(l==r)t[k].mins=a[l],t[k].maxs=a[r]; else { int mid=(l+r)>>1; build(k<<1,l,mid); build(k<<1|1,mid+1,r); t[k].mins=min(t[k<<1].mins,t[k<<1|1].mins); t[k].maxs=max(t[k<<1].maxs,t[k<<1|1].maxs); } } int askmaxs(int k,int l,int r) { int left=t[k].l,right=t[k].r; if(l<=left&&r>=right)return t[k].maxs; else { int mid=(left+right)>>1,ans=0; if(l<=mid)ans=askmaxs(k<<1,l,r); if(r>mid)ans=max(ans,askmaxs(k<<1|1,l,r)); return ans; } } int askmins(int k,int l,int r) { int left=t[k].l,right=t[k].r; if(l<=left&&r>=right)return t[k].mins; else { int mid=(left+right)>>1,ans=inf; if(l<=mid)ans=askmins(k<<1,l,r); if(r>mid)ans=min(ans,askmins(k<<1|1,l,r)); return ans; } } int main() { n=read();q=read(); for(int i=1;i<=n;i++)a[i]=read(); build(1,1,n); for(int i=1;i<=q;i++) { int u=read(),v=read(); printf("%d\n",askmaxs(1,u,v)-askmins(1,u,v)); } return 0; }