nrk009

SPARSE TABLE RANGE MINIMUM QUERY

Aug 9th, 2019
184
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.96 KB | None | 0 0
  1.  
  2. #include<bits/stdc++.h>
  3. using namespace std;
  4.  
  5. #define fast ios_base::sync_with_stdio(0);cin.tie(NULL);cout.tie(NULL)
  6. #define ll long long
  7. #define ld long double
  8. #define pb push_back
  9. #define fe first
  10. #define se second
  11. #define nl "\n"
  12. #define pp pair < ll , ll >
  13. #define sz(x) (ll)x.size()
  14. #define st(x) sort(x.begin(),x.end())
  15. #define rst(x) sort(x.rbegin(), x.rend())
  16. #define all(x) x.begin(),x.end()
  17. long double pi = 3.14159265358979323;
  18.  
  19. const double EPS = 1e-12;
  20. const int N = 1e5 + 5;
  21. const int mod = 1e9 + 7;
  22.  
  23. ll n , a[N],sparse[N][20],k;
  24. //using sparse table
  25.  ll query(ll l ,ll r){
  26.    ll j = log2(r - l  + 1);
  27.    return min(sparse[l][j],sparse[r-(1 << j) + 1][j]);
  28.   /* // elements taken = 2^j from l;
  29.    bache hue  = r - l + 1 - 2^j;
  30.    utna aage l ko srka dete hn to l + r - l + 1 - 2^j
  31.    to iska mtlb r - 2^j + 1 s 2^j elements*/
  32.  
  33.  }
  34.  
  35. int main()
  36. {
  37.     fast;
  38.     cin >> n ;
  39.     for(int i = 0 ; i  < n ; i++ )
  40.       cin >> a[i];
  41.    k = log2(n) + 1;
  42.    /*yahan p k ko itna isliye liye gya h maan ko n = 6 h to k ki value yahan p 3 aa jayegi
  43.    agr jyada le lete to 2^3 wo 8 ho jata itne elements hmare paaad nhi h
  44.    so k >= log2(n) + 1;*/
  45.  
  46.    for(int i = 0 ; i < n ; i++ ){
  47.       sparse[i][0] = a[i];
  48.    }
  49.    for(int j = 1 ; j  < k ; j++ ){
  50.       for(int i = 0 ; i + (1 << j) - 1 < n ; i++ ){
  51.          sparse[i][j] = min(sparse[i][j-1],sparse[i+(1 << (j-1))][j-1]);
  52.       }
  53.    }
  54.    /*is step ko smjhne k liye maan lo hmne 2^2 ko 2^1 aur 2^1 k baag m thod diya h
  55.    to understand take six elements and make the sparse table */
  56.  
  57.    /*for(int j = 0 ; j  < k ; j++ ){
  58.       for(int i = 0 ; i + (1 << j) - 1 < n ; i++ ){
  59.         cout << sparse[i][j] << " ";
  60.       }
  61.       cout << "\n";
  62.    }*/
  63.    ll q;
  64.    cin >> q;
  65.    while(q--){
  66.       ll l , r;
  67.       cin >> l >> r ;
  68.      // l--,r--;
  69.       cout << query(l,r) << "\n";
  70.    }
  71.    //build time O(nlog(n))
  72.    //query time O(1)
  73.    //query time for sum query is log2(n)
  74.    //that is most important
  75.    
  76.  
  77.  
  78.  
  79.  
  80.  
  81.  
  82.  
  83.  
  84.  
  85.  
  86.  
  87.  
  88.  
  89.  
  90.  
  91.  
  92.  
  93.  
  94.  
  95.  
  96.  
  97.    
  98.     return 0;
  99.    
  100. }
Advertisement
Add Comment
Please, Sign In to add comment