Advertisement
istinishat

RMQ(Sparce Table)

Oct 29th, 2016
231
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. #include<bits/stdc++.h>
  2. using namespace std;
  3.  
  4. #define si(n) scanf("%d",&n)
  5. #define MAX 100005
  6.  
  7. int arr[MAX],M[MAX][17];
  8.  
  9. void sparce(int n){
  10.     int i,j;
  11.     for(i=0;i<n;i++)
  12.         M[i][0]=i;
  13.     for(j=1;1<<j <= n;j++){
  14.         for(i=0;i+(1<<j)-1 <n;i++){
  15.             if(arr[M[i][j-1]]<arr[M[i+(1 << (j-1))][j-1]])
  16.                 M[i][j]=M[i][j-1];
  17.             else
  18.                 M[i][j]=M[i+ (1<<(j-1))][j-1];
  19.         }
  20.     }
  21. }
  22.  
  23. int RMQ(int i,int j){
  24.     int k=log2(j-i+1);
  25.     if(arr[M[i][k]]<=arr[M[j-(1<<k)+1][k]])
  26.         return M[i][k];
  27.     else
  28.         return M[j-(1<<k)+1][k];
  29. }
  30.  
  31. int main()
  32. {
  33.  
  34.     int n,i,j;
  35.     si(n);
  36.     for(i=0;i<n;i++)
  37.         si(arr[i]);
  38.     sparce(n);
  39.     cout<<"BUILD"<<endl;
  40.     for(;;){
  41.         cout<<"input : ";
  42.         si(i);si(j) ;
  43.         cout<<RMQ(i,j)<<endl;
  44.     }
  45. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement