dipBRUR

4

Nov 19th, 2017
76
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 3.15 KB | None | 0 0
  1. Wavlet Tree |
  2. |
  3. struct WAVELET_TREE { | // count nos in [l, r] equal to k
  4. int lo, hi; | int COUNT_EQUAL(int l, int r, int k) {
  5. WAVELET_TREE *l, *r; | if (l > r or k < lo or k > hi)
  6. vector <int> b; | return 0;
  7. // nos are in range [x, y] | if (lo == hi)
  8. // array indices are [from, to] | return (r - l + 1);
  9. WAVELET_TREE(int *from, int *to, int x, int y) { | int lb = b[l-1], rb = b[r], mid = (lo + hi) >> 1;
  10. lo = x; hi = y; | if (k <= mid)
  11. if (lo == hi or from >= to) | return this->l->COUNT_EQUAL(lb+1, rb, k);
  12. return; | else
  13. int mid = (x + y) >> 1; | return this->r->COUNT_EQUAL(l-lb, r-rb, k);
  14. auto f = [mid](int x) { | }
  15. return x <= mid; |
  16. }; | ~WAVELET_TREE() {
  17. b.reserve(to - from + 1); | delete l;
  18. b.push_back(0); // make it 1 indexed | delete r;
  19. for (auto it = from; it != to; it++) | }
  20. b.push_back(b.back() + f(*it)); | };
  21. auto pivot = stable_partition(from, to, f); |
  22. l = new WAVELET_TREE(from, pivot, lo, mid); |
  23. r = new WAVELET_TREE(pivot, to, mid + 1, hi); | Call :
  24. } | WAVELET_TREE *T;
  25. // k'th smallest element in[l,r] | T = new WAVELET_TREE(arr+1, arr+N+1, 1, MAXN)
  26. int KTH(int l, int r, int k) { |
  27. if (l > r) return 0; | MAXN = max number of the set
  28. if (lo == hi) return lo; | Don't use negetive number
  29. int lb = b[l-1], rb = b[r], inLeft = rb - lb; |
  30. if (inLeft <= k) |
  31. return this->l->KTH(lb+1, rb, k); | Complexity : nlogn
  32. else | QUERY : logn
  33. return this->r->KTH(l-lb, r-rb, k-inLeft); |
  34. } |
  35. // count nos in [l, r] less than or equal to k |
  36. int LTE(int l, int r, int k) { |
  37. if (l > r or k < lo) |
  38. return 0; |
  39. if (lo == hi) |
  40. return (r - l + 1); |
  41. int lb = b[l-1], rb = b[r]; |
  42. int total = this->l->LTE(lb+1, rb, k) + |
  43. this->r->LTE(l-lb, r-rb, k); |
  44. }
Add Comment
Please, Sign In to add comment