Advertisement
slash0t

non recursive segtree upd(i) get(l, r)

Jan 5th, 2025
88
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 0.71 KB | None | 0 0
  1. struct segtree {
  2.     vector<int> t;
  3.     int n;
  4.  
  5.     int ZERO = 0;
  6.  
  7.     segtree(int nn) : n(nn) {
  8.         t.assign(2 * n, ZERO);
  9.         build();
  10.     }
  11.  
  12.     segtree(vector<int> & a) {
  13.         n = a.size();
  14.         t.assign(2 * n, ZERO);
  15.         for (int i = 0; i < n; i++) t[i + n] = a[i];
  16.         build();
  17.     }
  18.  
  19.     int f(int x, int y) {
  20.         return x + y;
  21.     }
  22.  
  23.     void build() {
  24.         for (int i = n - 1; i > 0; --i) t[i] = f(t[i << 1], t[i << 1 | 1]);
  25.     }
  26.  
  27.     void upd(int p, int value) {
  28.         for (t[p += n] = value; p > 1; p >>= 1) t[p >> 1] = f(t[p], t[p ^ 1]);
  29.     }
  30.  
  31.     int get(int l, int r) {
  32.         int res = ZERO;
  33.         for (l += n, r += n; l < r; l >>= 1, r >>= 1) {
  34.             if (l & 1) res = f(res, t[l++]);
  35.             if (r & 1) res = f(res, t[--r]);
  36.         }
  37.         return res;
  38.     }
  39. };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement