Alex_tz307

ARBORE INDEXAT BINAR 2D

Aug 16th, 2021
674
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.51 KB | None | 0 0
  1. struct FenwickTree2D {
  2.   int n;
  3.   vector<vector<int>> vals, tree;
  4.  
  5.   FenwickTree2D(int N) {
  6.     n = N;
  7.     vals.resize(n + 1);
  8.     tree.resize(n + 1);
  9.   }
  10.  
  11.   void allocate(int x, int y) {
  12.     while (x <= n) {
  13.       vals[x].emplace_back(y);
  14.       x += x & -x;
  15.     }
  16.   }
  17.  
  18.   void init() {
  19.     for (int i = 1; i <= n; ++i) {
  20.       sort(vals[i].begin(), vals[i].end());
  21.       vals[i].erase(unique(vals[i].begin(), vals[i].end()), vals[i].end());
  22.       tree[i].resize(vals[i].size() + 1);
  23.     }
  24.   }
  25.  
  26.   void update(int x, int y, int val) {
  27.     while (x <= n) {
  28.       int pos = lower_bound(vals[x].begin(), vals[x].end(), y) - vals[x].begin();
  29.       for (++pos; pos < (int)tree[x].size(); pos += pos & -pos)
  30.         tree[x][pos] += val;
  31.       x += x & -x;
  32.     }
  33.   }
  34.  
  35.   int calc(int x, int val) {
  36.     int pos = upper_bound(vals[x].begin(), vals[x].end(), val) - vals[x].begin() - 1;
  37.     int ans = 0;
  38.     for (++pos; pos > 0; pos = pos & (pos - 1))
  39.       ans += tree[x][pos];
  40.     return ans;
  41.   }
  42.  
  43.   int query(int x, int val) {
  44.     int ans = 0;
  45.     while (x > 0) {
  46.       ans += calc(x, val);
  47.       x = x & (x - 1);
  48.     }
  49.     return ans;
  50.   }
  51.  
  52.   /* int query_interval(int st, int dr, int val) {
  53.     int ans = 0;
  54.     while (dr > 0) {
  55.       ans += calc(dr, val);
  56.       dr = dr & (dr - 1);
  57.     }
  58.     for (--st; st > 0; st = st & (st - 1))
  59.       ans -= calc(st, val);
  60.     return ans;
  61.   } */
  62.  
  63.   int query_interval(int st, int dr, int val) {
  64.     return query(dr, val) - query(st - 1, val);
  65.   }
  66. };
Advertisement
Add Comment
Please, Sign In to add comment