didedoshka

pers segtree

Mar 10th, 2021
303
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.35 KB | None | 0 0
  1. struct node {
  2.     int l, r;
  3.     int value;
  4.  
  5.     node() : l(-1), r(-1), value(0) {}
  6.  
  7.     node(int l, int r, int x) : l(l), r(r), value(x) {}
  8. };
  9.  
  10. const int N = 3000000;
  11. node tree[N];
  12. int last;
  13.  
  14. int build(int lx, int rx, const vector<int> &input) {
  15.     node a;
  16.     if (lx == rx - 1) {
  17.         a.value = input[lx];
  18.         tree[last] = a;
  19.         return last++;
  20.     }
  21.     int m = (lx + rx) / 2;
  22.     a.l = build(lx, m, input);
  23.     a.r = build(m, rx, input);
  24.     a.value = tree[a.l].value + tree[a.r].value;
  25.     tree[last] = a;
  26.     return last++;
  27. }
  28.  
  29. int update(int i, int v, int x, int lx, int rx) {
  30.     node a;
  31.     if (lx == rx - 1) {
  32.         a.value = tree[x].value + v;
  33.         tree[last] = a;
  34.         return last++;
  35.     }
  36.     int m = (lx + rx) / 2;
  37.     if (i < m) {
  38.         a.l = update(i, v, tree[x].l, lx, m);
  39.         a.r = tree[x].r;
  40.     } else {
  41.         a.l = tree[x].l;
  42.         a.r = update(i, v, tree[x].r, m, rx);
  43.     }
  44.     a.value = tree[a.l].value + tree[a.r].value;
  45.     tree[last] = a;
  46.     return last++;
  47. }
  48.  
  49. int sum(int l, int r, int x, int lx, int rx) {
  50.     if (r <= lx || rx <= l) {
  51.         return 0;
  52.     }
  53.     if (l <= lx && rx <= r) {
  54.         return tree[x].value;
  55.     }
  56.     int m = (lx + rx) / 2;
  57.     int left = sum(l, r, tree[x].l, lx, m);
  58.     int right = sum(l, r, tree[x].r, m, rx);
  59.     return left + right;
  60. }
Advertisement
Add Comment
Please, Sign In to add comment