poj 3264 Balanced Lineup
http://poj.org/problem?id=3264
1 #include <cstdio> 2 #include <cstring> 3 #include <algorithm> 4 #define maxn 5001000 5 using namespace std; 6 7 int a[maxn],x,y,N,Q,ans,max1,min1; 8 9 struct node 10 { 11 int l; 12 int r; 13 int tall; 14 int shorte; 15 }p[maxn]; 16 17 void build_tree(int i,int l,int r) 18 { 19 p[i].l=l; 20 p[i].r=r; 21 if(l==r) 22 { 23 p[i].tall=a[l]; 24 p[i].shorte=a[l]; 25 return; 26 } 27 int mid=(l+r)/2; 28 build_tree(i+i,l,mid); 29 build_tree(i+i+1,mid+1,r); 30 p[i].tall=max(p[i+i].tall,p[i+i+1].tall); 31 p[i].shorte=min(p[i+i].shorte,p[i+i+1].shorte); 32 } 33 34 void search1(int i,int l,int r) 35 { 36 if(p[i].l==l&&p[i].r==r) 37 { 38 max1=max(max1,p[i].tall); 39 min1=min(min1,p[i].shorte); 40 return ; 41 } 42 int mid=(p[i].l+p[i].r)/2; 43 if(r<=mid) 44 { 45 search1(i+i,l,r); 46 } 47 else if(l>mid) 48 { 49 search1(i+i+1,l,r); 50 } 51 else 52 { 53 search1(i+i,l,mid); 54 search1(i+i+1,mid+1,r); 55 } 56 } 57 58 int main() 59 { 60 while(scanf("%d%d",&N,&Q)!=EOF) 61 { 62 for(int i=1; i<=N; i++) 63 { 64 scanf("%d",&a[i]); 65 } 66 build_tree(1,1,N); 67 for(int i=0; i<Q; i++) 68 { 69 max1=-1; 70 min1=maxn; 71 scanf("%d%d",&x,&y); 72 search1(1,x,y); 73 printf("%d\n",max1-min1); 74 } 75 } 76 return 0; 77 }
用动态规划解决的;
1 #include <cstdio> 2 #include <cstring> 3 #include <algorithm> 4 #include <cmath> 5 #define maxn 500010 6 using namespace std; 7 8 int maxsum[maxn][30],a[maxn],N,Q,minsum[maxn][30],x,y; 9 10 int main() 11 { 12 while(scanf("%d%d",&N,&Q)!=EOF) 13 { 14 for(int i=1; i<=N; i++) 15 { 16 scanf("%d",&a[i]); 17 } 18 for(int i=1; i<=N; i++) 19 { 20 maxsum[i][0]=a[i]; 21 minsum[i][0]=a[i]; 22 } 23 int m=(int)(log(N*1.0)/log(2.0)); 24 for(int j=1; j<=m; j++) 25 { 26 for(int i=1; i<=N; i++) 27 { 28 if(i+(1<<j)-1<=N) 29 { 30 maxsum[i][j]=max(maxsum[i][j-1],maxsum[i+(1<<(j-1))][j-1]); 31 minsum[i][j]=min(minsum[i][j-1],minsum[i+(1<<(j-1))][j-1]); 32 } 33 } 34 } 35 for(int i=0; i<Q; i++) 36 { 37 scanf("%d%d",&x,&y); 38 int k=(int)(log(y-x+1.0)/(log(2.0))); 39 printf("%d\n",max(maxsum[x][k],maxsum[y-(1<<k)+1][k])-min(minsum[x][k],minsum[y-(1<<k)+1][k])); 40 } 41 } 42 return 0; 43 }