poj3264Balanced Lineup(RMQ)
http://poj.org/problem?id=3264
RMQ讲解 http://dongxicheng.org/structure/lca-rmq/
j = log2K
dp[i][j] = max(dp[i][j-1]+dp[i+(1<<(j-1))][j-1];
1 #include <iostream> 2 #include<cstdio> 3 #include<cstring> 4 #include<stdlib.h> 5 #include<algorithm> 6 #include<cmath> 7 using namespace std; 8 #define N 50005 9 int minz[N][40],maxz[N][40]; 10 void init(int n) 11 { 12 int i,j,o = floor(log10(double(n))/log10(double(2))); 13 for(j = 1 ; j <= o ; j++) 14 for(i = 1 ; i <= n+1-(1<<j) ; i++) 15 { 16 maxz[i][j] = max(maxz[i][j-1],maxz[i+(1<<(j-1))][j-1]); 17 minz[i][j] = min(minz[i][j-1],minz[i+(1<<(j-1))][j-1]); 18 } 19 } 20 int main() 21 { 22 int i,n,q,h; 23 while(scanf("%d%d",&n,&q)!=EOF) 24 { 25 for(i = 1; i <= n ; i++) 26 { 27 scanf("%d",&h); 28 minz[i][0] = h; 29 maxz[i][0] = h; 30 } 31 init(n); 32 while(q--) 33 { 34 int a,b,t; 35 scanf("%d%d",&a,&b); 36 if(a>b) 37 { 38 t = a;a = b; b = t; 39 } 40 int o = floor(log10(double(b-a+1))/log10(double(2))); 41 printf("%d\n",max(maxz[a][o],maxz[b-(1<<o)+1][o])-min(minz[a][o],minz[b-(1<<o)+1][o])); 42 } 43 } 44 return 0; 45 }