维护区间最值的模板题。
1.树状数组
1 #include<bits/stdc++.h> 2 //树状数组做法 3 using namespace std; 4 const int N=5e4+10; 5 int m,ma[N],mi[N],n,c[N]; 6 7 int lowbit(int x){ 8 return x&(-x); 9 } 10 11 void ins(int x,int v){ 12 while(x<=n){ 13 ma[x]=max(ma[x],v);mi[x]=min(mi[x],v); 14 x+=lowbit(x); 15 } 16 } 17 18 int que(int L,int R){ 19 int maxx=-1,minn=1e9; 20 while(L<=R){ 21 for(;R-lowbit(R)>=L;R-=lowbit(R)) maxx=max(maxx,ma[R]),minn=min(minn,mi[R]); 22 maxx=max(c[R],maxx);minn=min(minn,c[R]); 23 R--; 24 } 25 return maxx-minn; 26 } 27 28 int main(){ 29 memset(mi,0x3f,sizeof(mi)); 30 memset(ma,0,sizeof(ma)); 31 scanf("%d%d",&n,&m); 32 for(int i=1;i<=n;i++){ 33 int x;scanf("%d",&x); 34 ins(i,x); 35 c[i]=x; 36 } 37 while(m--){ 38 int a,b; 39 scanf("%d%d",&a,&b); 40 cout<<que(a,b)<<endl; 41 } 42 }
2.线段树
1 #include<bits/stdc++.h> 2 //线段树做法 3 using namespace std; 4 const int N=5e4+10; 5 #define lson l,mid,pos<<1 6 #define rson mid+1,r,pos<<1|1 7 int maxx[N<<2],minn[N<<2],MAX,MIN; 8 9 void up(int pos){ 10 maxx[pos]=max(maxx[pos<<1],maxx[pos<<1|1]); 11 minn[pos]=min(minn[pos<<1],minn[pos<<1|1]); 12 } 13 14 void build(int l,int r,int pos){ 15 if(l==r){ 16 int x;scanf("%d",&x); 17 maxx[pos]=minn[pos]=x; 18 return ; 19 } 20 int mid=(l+r)>>1; 21 build(lson);build(rson); 22 up(pos); 23 } 24 25 void query(int L,int R,int l,int r,int pos){ 26 if(L<=l && R>=r){ 27 MAX=max(MAX,maxx[pos]); 28 MIN=min(MIN,minn[pos]); 29 return ; 30 } 31 int mid=(l+r)>>1; 32 if(L<=mid) query(L,R,lson); 33 if(R>mid) query(L,R,rson); 34 } 35 36 int main(){ 37 int n,m; 38 scanf("%d%d",&n,&m); 39 build(1,n,1); 40 while(m--){ 41 MAX=0,MIN=1e9; 42 int a,b;scanf("%d%d",&a,&b); 43 query(a,b,1,n,1); 44 cout<<MAX-MIN<<endl; 45 } 46 return 0; 47 }