Advertisement
dipBRUR

Wavelet Tree

Feb 2nd, 2018
148
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.94 KB | None | 0 0
  1. // Wavelet Tree
  2.  
  3. const int MAX = 1e6;
  4.  
  5. struct wavelet_tree{
  6.     #define vi vector<int>
  7.     #define pb push_back
  8.     int lo, hi;
  9.     wavelet_tree *l, *r;
  10.     vi b;
  11.    
  12.     //nos are in range [x,y]
  13.     //array indices are [from, to)
  14.     wavelet_tree(int *from, int *to, int x, int y) {
  15.         lo = x, hi = y;
  16.         if(lo == hi or from >= to)
  17.             return;
  18.         int mid = (lo+hi)/2;
  19.         auto f = [mid](int x) {
  20.             return x <= mid;
  21.         };
  22.         b.reserve(to-from+1);
  23.         b.pb(0);
  24.         for(auto it = from; it != to; it++)
  25.             b.pb(b.back() + f(*it));
  26.         //see how lambda function is used here 
  27.         auto pivot = stable_partition(from, to, f);
  28.         l = new wavelet_tree(from, pivot, lo, mid);
  29.         r = new wavelet_tree(pivot, to, mid+1, hi);
  30.     }
  31.    
  32.     //kth smallest element in [l, r]
  33.     int kth(int l, int r, int k){
  34.         if(l > r)
  35.             return 0;
  36.         if(lo == hi)
  37.             return lo;
  38.         int inLeft = b[r] - b[l-1];
  39.         int lb = b[l-1]; //amt of nos in first (l-1) nos that go in left
  40.         int rb = b[r];   //amt of nos in first (r) nos that go in left
  41.         if(k <= inLeft)
  42.             return this->l->kth(lb+1, rb , k);
  43.         return this->r->kth(l-lb, r-rb, k-inLeft);
  44.     }
  45.    
  46.     //count of nos in [l, r] Less than or equal to k
  47.     int LTE(int l, int r, int k) {
  48.         if(l > r or k < lo)
  49.             return 0;
  50.         if(hi <= k)
  51.             return r - l + 1;
  52.         int lb = b[l-1], rb = b[r];
  53.         return this->l->LTE(lb+1, rb, k) + this->r->LTE(l-lb, r-rb, k);
  54.     }
  55.  
  56.     //count of nos in [l, r] equal to k
  57.     int count(int l, int r, int k) {
  58.         if(l > r or k < lo or k > hi)
  59.             return 0;
  60.         if(lo == hi)
  61.             return r - l + 1;
  62.         int lb = b[l-1], rb = b[r], mid = (lo+hi)/2;
  63.         if(k <= mid)
  64.             return this->l->count(lb+1, rb, k);
  65.         return this->r->count(l-lb, r-rb, k);
  66.     }
  67.     ~wavelet_tree() {
  68.         delete l;
  69.         delete r;
  70.     }
  71. };
  72.  
  73. int main()
  74. {
  75.     // Take Input, save value in another array
  76.     wavelet_tree *T;
  77.     T = new wavelet_tree(data + 1, data + N + 1, 1, MAXN);
  78.     // Output
  79. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement