Advertisement
nullzero

RMQ

Mar 7th, 2013
95
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.23 KB | None | 0 0
  1. #include <iostream>
  2. #include <cmath>
  3.  
  4. using namespace std;
  5.  
  6. const int LOGN = 20;
  7. const int MAXN = 100000;
  8.  
  9. int table[LOGN][MAXN];
  10. int A[MAXN];
  11.  
  12. void preprocess(int n){
  13.     for(int i = 0; i < n; ++i) table[0][i] = A[i];
  14.     for(int i = 1; i <= LOGN; ++i){
  15.         for(int j = 0; j < n; ++j){
  16.             if(j + (1 << i) - 1 >= n) break;
  17.             // table[0][1] => min(A[1..1])
  18.             // table[1][1] => min(A[1..2])
  19.             // table[2][1] => min(A[1..4])
  20.             // table[i][j] => min(A[j..j+2^i-1])
  21.             // table[i][j] => min(A[j..j+2^(i-1)-1], A[j+2^(i-1)..j+2^i-1)
  22.             table[i][j] = min(table[i - 1][j], table[i - 1][j + (1 << (i - 1))]);
  23.         }
  24.     }
  25. }
  26.  
  27. int query(int a, int b){
  28.     // min(A[a..a+2^x-1], A[b-2^x+1..b])
  29.     // a+2^x-1 <= b
  30.     // 2^x <= b - a + 1
  31.     // x log 2 <= log(b - a + 1)
  32.     int x = int(log2(b - a + 1));
  33.     return min(table[x][a], table[x][b - (1 << x) + 1]);
  34. }
  35.  
  36. int main(){
  37.     A[0] = 1;
  38.     A[1] = 2;
  39.     A[2] = 3;
  40.     preprocess(3);
  41.     cout << query(0, 0) << endl;
  42.     cout << query(1, 1) << endl;
  43.     cout << query(2, 2) << endl;
  44.     cout << query(0, 1) << endl;
  45.     cout << query(1, 2) << endl;
  46.     cout << query(0, 2) << endl;
  47.     return 0;
  48. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement