Advertisement
a_pramanik

Sparse Table

Jun 15th, 2016
94
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.28 KB | None | 0 0
  1. #include <bits/stdc++.h>
  2. using namespace std;
  3.  
  4. #define pb push_back
  5. #define ll long long int
  6. #define inf 2000000000
  7. #define pi (2.0*acos(0.0))
  8. #define vsort(v)   sort(v.begin(),v.end())
  9. #define ull unsigned long long int
  10. #define mem(a, b) memset(a, b, sizeof a)
  11.  
  12. int a[100005], tab[100005][25];
  13.  
  14. int query(int l, int r){
  15.  
  16.         int d = (r-l)+1;
  17.         int x = 31- (__builtin_clz(d));
  18.  
  19.         int res = min(tab[x][l], tab[x][r-(1<<x)+1]);
  20.         return res;
  21.  
  22. }
  23.  
  24. int main()
  25.  
  26. {
  27.         int i, j, k, q, n, r, c, s, e;
  28.         while(scanf("%d%d", &n, &q)==2){
  29.             for(i=1; i<=n; i++){
  30.                 scanf("%d", &a[i]);
  31.                 tab[0][i]=a[i];
  32.             }
  33.  
  34.             for(r =1; (1<<r)<=n; r++){
  35.                 for(c=1; c+(1<<(r-1))<=n; c++){
  36.                     tab[r][c]=min(tab[r-1][c], tab[r-1][c+(1<<(r-1))]);
  37.                 }
  38.             }
  39.  
  40.             /*for(r =1; (1<<r)<=n; r++){
  41.                 for(c=1; c+(1<<(r-1))<=n; c++){
  42.                     printf("%d ", tab[r][c]);
  43.                 }
  44.                 printf("\n");
  45.             }*/
  46.  
  47.             for(i=1; i<=q; i++){
  48.                 scanf("%d%d", &s, &e);
  49.                 printf("%d\n", query(s, e));
  50.             }
  51.  
  52.         }
  53.         return 0;
  54. }
  55.  
  56. //8 10
  57. //7 3 4 5 1 2 9 8
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement