Advertisement
Guest User

Untitled

a guest
Sep 18th, 2019
98
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.68 KB | None | 0 0
  1. struct SegmentTree {
  2.     vector<ll> tree, lazy, l, r;
  3.  
  4.     SegmentTree(int size) : tree(4 * size), lazy(4 * size), l(4 * size), r(4 * size) {
  5.         init(1, 0, size - 1);
  6.     }
  7.      
  8.     // Functions to update when query changes =============================
  9.  
  10.     ll best(ll lCalc, ll rCalc) {
  11.         return lCalc + rCalc;
  12.     }
  13.  
  14.     void upd(int i) {
  15.         tree[i] = best(tree[i << 1] + lazy[i << 1], tree[i << 1 | 1] + lazy[i << 1 | 1]);
  16.     }
  17.  
  18.      
  19.     void prob(int i) {
  20.         lazy[i << 1] += lazy[i];
  21.         lazy[i << 1 | 1] += lazy[i];
  22.         lazy[i] = 0;
  23.     }
  24.  
  25.     // ====================================================================
  26.      
  27.     void inc(int s, int e, ll v, int i = 1) {
  28.         if(s > r[i] || e < l[i])
  29.             return;
  30.  
  31.         if(s <= l[i] && e >= r[i]) {
  32.             lazy[i] += v;
  33.             return;
  34.         }
  35.      
  36.         prob(i);
  37.      
  38.         inc(s, e, v, i << 1);
  39.         inc(s, e, v, i << 1 | 1);
  40.      
  41.         upd(i);
  42.     }
  43.  
  44.      
  45.     ll qry(int s, int e, int i = 1) {
  46.         if(s > r[i] || e < l[i]) // change the return value depending on the query
  47.             return 0;
  48.  
  49.         if(s <= l[i] && e >= r[i]) // may change if the query change
  50.             return tree[i] + lazy[i];
  51.      
  52.         prob(i);
  53.      
  54.         ll lCalc = qry(s, e, i << 1);
  55.         ll rCalc = qry(s, e, i << 1 | 1);
  56.      
  57.         upd(i);
  58.      
  59.         return best(lCalc, rCalc);
  60.     }
  61.      
  62.     void init(int i, int s, int e) {
  63.         l[i] = s;
  64.         r[i] = e;
  65.      
  66.         if(s == e)
  67.             return;
  68.      
  69.         int m = s + ((e - s) >> 1);
  70.  
  71.         init(i << 1, s, m);
  72.         init(i << 1 | 1, m + 1, e);
  73.     }
  74. };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement