http://poj.org/problem?id=3264
RMQ 模板题
参考资料:http://wenku.baidu.com/view/53e2b6ed4afe04a1b071deb5.html
代码:
#include<iostream> #include<cstdio> #include<cstring> #include<string> #include<cmath> #include<queue> #include<algorithm> #include<stack> using namespace std; const int N=50010; const int M=16; int high[N]; int Bmax[N][M]; int Bmin[N][M]; void Bmq(int n) { int J=log(n)/log(2); for(int j=1;j<=J;++j) { int I=n+1-(1<<j); for(int i=1;i<=I;++i) { Bmax[i][j]=max(Bmax[i][j-1],Bmax[i+(1<<(j-1))][j-1]); Bmin[i][j]=min(Bmin[i][j-1],Bmin[i+(1<<(j-1))][j-1]); } } } int findx(int l,int r) { int x=1; while((1<<x)<=(r-l+1)) { ++x; } return (x-1); } int main() { int n,m; while(scanf("%d %d",&n,&m)!=EOF) { for(int i=1;i<=n;++i) { scanf("%d",&high[i]); Bmax[i][0]=high[i]; Bmin[i][0]=high[i]; } Bmq(n); while(m--) { int l,r; scanf("%d %d",&l,&r); int x=findx(l,r); int k=(int)(1<<x); printf("%d\n",max(Bmax[l][x],Bmax[r+1-k][x])-min(Bmin[l][x],Bmin[r+1-k][x])); } } return 0; }