POJ 3264-Balanced Lineup-RMQ问题
裸RMQ问题
1 #include <cstdio> 2 #include <algorithm> 3 #include <cstring> 4 5 using namespace std; 6 7 const int MAXN = 50010; 8 9 int min_dp[MAXN][20],max_dp[MAXN][20]; 10 int min_mm[MAXN],max_mm[MAXN]; 11 int b[MAXN]; 12 int N,Q; 13 14 void min_initRMQ(int n,int b[]) 15 { 16 min_mm[0] = -1; 17 for(int i=1;i<=n;i++) 18 { 19 min_mm[i] = ( (i&(i-1)) == 0) ? min_mm[i-1]+1 : min_mm[i-1]; 20 min_dp[i][0] = b[i]; 21 } 22 for(int j=1;j<=min_mm[n];j++) 23 for(int i=1;i + (1<<j) - 1 <= n;i++) 24 min_dp[i][j] = min(min_dp[i][j-1],min_dp[i+(1<<(j-1))][j-1]); 25 26 } 27 28 int min_rmq(int x,int y) 29 { 30 int k = min_mm[y-x+1]; 31 return min(min_dp[x][k],min_dp[y-(1<<k)+1][k]); 32 } 33 34 35 void max_initRMQ(int n,int b[]) 36 { 37 max_mm[0] = -1; 38 for(int i=1;i<=n;i++) 39 { 40 max_mm[i] = ( (i&(i-1)) == 0) ? max_mm[i-1]+1 : max_mm[i-1]; 41 max_dp[i][0] = b[i]; 42 } 43 for(int j=1;j<=max_mm[n];j++) 44 for(int i=1;i + (1<<j) - 1 <= n;i++) 45 max_dp[i][j] = max(max_dp[i][j-1],max_dp[i+(1<<(j-1))][j-1]); 46 47 } 48 49 int max_rmq(int x,int y) 50 { 51 int k = max_mm[y-x+1]; 52 return max(max_dp[x][k],max_dp[y-(1<<k)+1][k]); 53 } 54 55 int main() 56 { 57 //freopen("input.in","r",stdin); 58 while(~scanf("%d%d",&N,&Q)) 59 { 60 for(int i=1;i<=N;i++) 61 { 62 scanf("%d",&b[i]); 63 } 64 min_initRMQ(N,b); 65 max_initRMQ(N,b); 66 67 for(int i=0,l,r;i<Q;i++) 68 { 69 scanf("%d%d",&l,&r); 70 printf("%d\n",max_rmq(l,r) - min_rmq(l,r) ); 71 //printf("%d\n",max_rmq(l,r)); 72 } 73 } 74 }