POJ3264 【RMQ基础题—ST-线段树】
ST算法Code:
//#include<bits/stdc++.h> #include<cstdio> #include<math.h> #include<iostream> #include<queue> #include<algorithm> #include<string.h> using namespace std; typedef long long LL; const int N=5e4+10; int n,q; int a[N]; int f1[N][30]; int f2[N][30]; void ST() { for(int i=1;i<=n;i++) f1[i][0]=f2[i][0]=a[i]; int nlog=(int)(log(double(n))/log(2.0)); for(int j=1;j<=nlog;j++) { for(int i=1;i<=n;i++) { if(i+(1<<j)-1<=n) { f1[i][j]=min(f1[i][j-1],f1[i+(1<<(j-1))][j-1]); f2[i][j]=max(f2[i][j-1],f2[i+(1<<(j-1))][j-1]); } } } } int RMQ(int l,int r) { int nlog=(int)(log(double(r-l+1))/log(2.0)); int mi=min(f1[l][nlog],f1[r-(1<<nlog)+1][nlog]); int ma=max(f2[l][nlog],f2[r-(1<<nlog)+1][nlog]); return ma-mi; } int main() { int l,r; while(scanf("%d%d",&n,&q)!=EOF) { for(int i=1;i<=n;i++) scanf("%d",&a[i]); ST(); while(q--) { scanf("%d%d",&l,&r); printf("%d\n",RMQ(l,r)); } } return 0; }
线段树Code:
#include<cstdio> #include<iostream> #include<string.h> #include<algorithm> using namespace std; const int N=50007; struct st{ int left,right; int mina; int maxa; }; st q[N*4]; int n,m; void build(int num,int L,int R) { q[num].left=L; q[num].right=R; if(L==R) { scanf("%d",&q[num].maxa); q[num].mina=q[num].maxa; return; } build(2*num,L,(L+R)/2); build(2*num+1,(L+R)/2+1,R); q[num].mina=min(q[2*num].mina,q[2*num+1].mina); q[num].maxa=max(q[2*num].maxa,q[2*num+1].maxa); } int ans1; int ans2; int get_max(int num,int s,int t) { if(q[num].left>=s&&q[num].right<=t) return q[num].maxa; int mid=(q[num].left+q[num].right)/2; if(mid>=t) return get_max(2*num,s,t); else if(mid<s) return get_max(2*num+1,s,t); else{ return max(get_max(2*num,s,mid),get_max(2*num+1,mid+1,t)); } } int get_min(int num,int s,int t) { if(q[num].left>=s&&q[num].right<=t) return q[num].mina; int mid=(q[num].left+q[num].right)/2; if(mid>=t) return get_min(2*num,s,t); else if(mid<s) return get_min(2*num+1,s,t); else{ return min(get_min(2*num,s,mid),get_min(2*num+1,mid+1,t)); } } int main() { scanf("%d%d",&n,&m); build(1,1,n); while(m--) { int a,b; scanf("%d%d",&a,&b); printf("%d\n",get_max(1,a,b)-get_min(1,a,b)); } return 0; }