Advertisement
istinishat

RMQ

Aug 7th, 2018
1,031
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. int a[MAX],b[MAX],mx[MAX][20],mn[MAX][20],n;
  2. //preprocess O(nlogn) , quary O(1) ; no update can be handaled
  3. //from topcoder, array is 1-indexed
  4. void RMQ()
  5. {
  6.     int i,j;
  7.     for(i=1;i<=n;i++)mx[i][0]=i;
  8.     for(i=1;i<=n;i++)mn[i][0]=i;
  9.  
  10.     for(j=1;(1<<j)<=n;j++){
  11.  
  12.         for(i=1;i+(1<<j)-1<=n;i++){
  13.             if(a[mx[i][j-1]]>a[mx[i+(1<<(j-1))][j-1]])
  14.                 mx[i][j]=mx[i][j-1];
  15.             else mx[i][j]=mx[i+(1<<(j-1))][j-1];
  16.         }
  17.  
  18.         for(i=1;i+(1<<j)-1<=n;i++){
  19.             if(b[mn[i][j-1]]<b[mn[i+(1<<(j-1))][j-1]])
  20.                 mn[i][j]=mn[i][j-1];
  21.             else mn[i][j]=mn[i+(1<<(j-1))][j-1];
  22.         }
  23.  
  24.     }
  25. }
  26.  
  27.  
  28. int mylog[3*MAX];
  29.  
  30. void calclog()
  31. {
  32.     int x=1,i=1,pw=0;
  33.     while(x<MAX){
  34.         x*=2;
  35.         for(;i<x;i++){
  36.             mylog[i]=pw;
  37.         }
  38.         pw++;
  39.         mylog[i]=pw;
  40.         i++;
  41.     }
  42. }
  43.  
  44. int get_mx(int i,int j)
  45. {
  46.     int k=mylog[j-i+1];
  47.     return max(a[mx[i][k]],a[mx[j-(1<<k)+1][k]]);
  48. }
  49.  
  50. int get_mn(int i,int j)
  51. {
  52.     int k=mylog[j-i+1];
  53.     return min(b[mn[i][k]],b[mn[j-(1<<k)+1][k]]);
  54. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement