Advertisement
AlejandroGY

Fenwick 2D

Apr 25th, 2018
92
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.34 KB | None | 0 0
  1. #include <bits/stdc++.h>
  2.  
  3. struct FenwickTree2D {
  4.     std::vector<std::vector<int>> a;
  5.     int n, m;
  6.  
  7.     FenwickTree2D(int n, int m)
  8.     : n(n), m(m), a(n, std::vector<int>(m)) {
  9.     }
  10.  
  11.     void update(int x, int y, int val) {
  12.         int y1;
  13.         while (x < n) {
  14.             y1 = y;
  15.             while (y1 < m) {
  16.                 a[x][y1] += val;
  17.                 y1 |= y1 + 1;
  18.             }
  19.             x |= x + 1;
  20.         }
  21.     }
  22.  
  23.     int get(int x, int y) {
  24.         int res = 0;
  25.         int y1;
  26.         while (x >= 0) {
  27.             y1 = y;
  28.             while (y1 >= 0) {
  29.                 res += a[x][y1];
  30.                 y1 = (y1 & (y1 + 1)) - 1;
  31.             }
  32.             x = (x & (x + 1)) - 1;
  33.         }
  34.         return res;
  35.  
  36.     }
  37.  
  38.     int get(int x1, int y1, int x2, int y2) {
  39.         int res = get(x2, y2);
  40.         res -= get(x1 - 1, y2);
  41.         res -= get(x2, y1 - 1);
  42.         res += get(x1 - 1, y1 - 1);
  43.         return res;
  44.     }
  45. };
  46.  
  47. int main( ) {
  48.     std::ios_base::sync_with_stdio(0);
  49.     std::cin.tie(0);
  50.  
  51.     int cases;
  52.     std::cin >> cases;
  53.     for (int ti = 0; ti < cases; ++ti) {
  54.         if (ti > 0) {
  55.             std::cout << "\n";
  56.         }
  57.  
  58.         int n;
  59.         std::cin >> n;
  60.         FenwickTree2D arbol(n + 1, n + 1);
  61.  
  62.         std::string op;
  63.         std::cin >> op;
  64.         while (op != "END") {
  65.            
  66.             if (op == "SUM") {
  67.                 int x1, y1, x2, y2;
  68.                 std::cin >> x1 >> y1 >> x2 >> y2;
  69.                 std::cout << arbol.get(x1, y1, x2, y2) << "\n";
  70.             } else if (op == "SET") {
  71.                 int x, y, num;
  72.                 std::cin >> x >> y >> num;
  73.                 arbol.update(x, y, num);
  74.             }
  75.             std::cin >> op;
  76.         }
  77.     }
  78. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement