Matrix_code

data-structure - Sparse Table(RMQ)

Oct 10th, 2016 (edited)
175
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.58 KB | None | 0 0
  1. /*
  2.     Range Minimum Query (Sparse Table).
  3.     Preprocess(O(nlogn),Query(O(1))
  4.     Indexing- [1,n].
  5. */
  6. int dp[N][22];
  7. int mn[N];
  8. void initRMQ(int n,int a[])
  9. {
  10.     mn[0]=-1;
  11.     for(int i= 1;i<=n;i++) dp[i][0] = a[i], mn[i]=mn[i/2]+1;
  12.     for(int j= 1; (1<<j) <= n; j ++ ){
  13.         for(int i = 1; i + (1<<j) - 1 <= n ; i ++ ) {
  14.             dp[i][j] = min(dp[i][j-1] , dp[i + (1<<(j-1))][j-1]);
  15.         }
  16.     }
  17. }
  18. int askRMQ(int L,int R)
  19. {
  20.     int k = mn[R-L+1];
  21.     return min(dp[L][k], dp[R - (1<<k) + 1][k]);
  22. }
  23. /*======================================================================*/
Add Comment
Please, Sign In to add comment