Advertisement
Ali-ElMasry

SegmentTree

Nov 22nd, 2019
171
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.93 KB | None | 0 0
  1. struct node {
  2.     ll val, lazy;
  3.     node(ll _val = 0, ll _lazy = 0) :
  4.      val(_val), lazy(_lazy) {}
  5. };
  6.  
  7. struct SegmentTree {
  8.     const node invalid = node(INF,0);
  9.    
  10.     int size;
  11.     vector<int> l, r;
  12.     vector<node> tree;
  13.    
  14.     node val(node t) {
  15.         t.val += t.lazy;
  16.         t.lazy = 0;
  17.         return t;
  18.     }
  19.    
  20.     void updLazy(node& t, ll v) {
  21.         t.lazy += v;
  22.     }
  23.    
  24.     node best(node x, node y) {
  25.         return x.val < y.val ? x : y;
  26.     }
  27.    
  28.     void modify(int i) {
  29.         tree[i] = best(val(tree[i << 1]), val(tree[i << 1 | 1]));
  30.     }
  31.    
  32.     void prob(int i) {
  33.         updLazy(tree[i << 1], tree[i].lazy);
  34.         updLazy(tree[i << 1 | 1], tree[i].lazy);
  35.         tree[i].lazy = 0;
  36.     }
  37.    
  38.     SegmentTree(int _size) :
  39.      size(_size), l(4 * _size), r(4 * _size) , tree(4 * _size) {
  40.             init(0, _size - 1);
  41.          }
  42.      
  43.      void update(int s, int e, ll v, int i = 1) {
  44.          if (s > r[i] || e < l[i])
  45.             return;
  46.            
  47.         if (l[i] >= s && r[i] <= e) {
  48.             updLazy(tree[i], v);
  49.             return;
  50.         }
  51.        
  52.         prob(i);
  53.        
  54.         update(s, e, v, i << 1);
  55.         update(s, e, v, i << 1 | 1);
  56.        
  57.         modify(i);
  58.      }
  59.      
  60.      node query(int s, int e, int i = 1) {
  61.          if (s > r[i] || e < l[i])
  62.             return invalid;
  63.            
  64.         if (l[i] >= s && r[i] <= e) {
  65.             return val(tree[i]);
  66.         }
  67.            
  68.         prob(i);
  69.        
  70.         node lhs = query(s, e, i << 1);
  71.         node rhs = query(s, e, i << 1 | 1);
  72.  
  73.         modify(i);
  74.        
  75.         return best(lhs, rhs);
  76.      }
  77.    
  78.     void init(int s, int e, int i = 1) {
  79.         l[i] = s;
  80.         r[i] = e;
  81.        
  82.         if (s == e)
  83.             return;
  84.            
  85.         int m = s + ((e - s) >> 1);
  86.        
  87.         init(s, m, i << 1);
  88.         init(m + 1, e, i << 1 | 1);
  89.     }
  90. };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement