4eyes4u

Implicit segment tree

Feb 17th, 2017
172
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.13 KB | None | 0 0
  1. /*
  2. Implicit segment tree
  3.  
  4. Requires O(Nlog(val)) memory
  5. */
  6.  
  7. #include <bits/stdc++.h>
  8. #define mid (left+(right-left)/2)
  9. using namespace std;
  10.  
  11. struct Node
  12. {
  13.     int val;
  14.     Node *l, *r;
  15. };
  16.  
  17. void update (Node *v, int left, int right, int x, int val)
  18. {
  19.     if (left==right)
  20.     {
  21.         v->val=val;
  22.         return;
  23.     }
  24.  
  25.     if (x<=mid)
  26.     {
  27.         if (v->l==NULL) v->l=new Node();
  28.         update (v->l, left, mid, x, val);
  29.         v->val+=(v->l)->val;
  30.     }
  31.     else
  32.     {
  33.         if (v->r==NULL) v->r=new Node();
  34.         update (v->r, mid+1, right, x, val);
  35.         v->val+=(v->r)->val;
  36.     }
  37. }
  38.  
  39. int query (Node *v, int left, int right, int l, int r)
  40. {
  41.     if (l<=left && right<=r) return v->val;
  42.  
  43.     int ret=0;
  44.     if (l<=mid)
  45.     {
  46.         if (v->l==NULL) return 0;
  47.         return query(v->l, left, mid, l, r);
  48.     }
  49.     if (r>mid)
  50.     {
  51.         if (v->r==NULL) return 0;
  52.         return query(v->r, mid+1, right, l, r);
  53.     }
  54. }
  55.  
  56. int main()
  57. {
  58.     int N=1e9;
  59.  
  60.     Node *root=new Node();
  61.  
  62.     update (root, 1, N, (int)1e7, (int)1e7);
  63.  
  64.     cout << query(root, 1, N, 1, N);
  65.  
  66.     return 0;
  67. }
Advertisement
Add Comment
Please, Sign In to add comment