题目连接:http://poj.org/problem?id=3264
1 #include<cstdio> 2 #include<cstring> 3 #include<cmath> 4 #include<algorithm> 5 using namespace std; 6 const int maxn=500010; 7 const int inf=0x3f3f3f3f; 8 9 int maxx[maxn][21]; 10 int minn[maxn][21]; 11 int n,q; 12 int l,r; 13 int main() 14 { 15 while(scanf("%d%d",&n,&q)!=EOF) 16 { 17 for(int i=1;i<=n;i++) 18 { 19 scanf("%d",&maxx[i][0]); 20 minn[i][0]=maxx[i][0]; 21 } 22 // for(int i=0;i<21;i++) 23 // { 24 // maxx[0][i]=-inf; 25 // minn[0][i]=inf; 26 // } 27 int len=log2(n); 28 for(int j=1;j<=len;j++) 29 for(int i=1;(i+(1<<j)-1)<=n;i++) 30 { 31 maxx[i][j]=max(maxx[i][j-1],maxx[i+(1<<j-1)][j-1]); 32 minn[i][j]=min(minn[i][j-1],minn[i+(1<<j-1)][j-1]); 33 } 34 while(q--) 35 { 36 scanf("%d%d",&l,&r); 37 38 int k=log2(r-l+1); 39 int maxans=max(maxx[l][k],maxx[r-(1<<k)+1][k]); 40 int minans=min(minn[l][k],minn[r-(1<<k)+1][k]); 41 printf("%d ",maxans-minans); 42 } 43 44 } 45 }