-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathFenwick_Tree_2D_Point_Update_Range_Query.cpp
More file actions
105 lines (94 loc) · 2.44 KB
/
Fenwick_Tree_2D_Point_Update_Range_Query.cpp
File metadata and controls
105 lines (94 loc) · 2.44 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
#include <bits/stdc++.h>
using namespace std;
// Point Update & Range Query, O(log(n)*log(m))
template <typename T>
struct FenwickTree2D {
int n, m;
vector<vector<T>> f;
FenwickTree2D() : n(0), m(0) {}
FenwickTree2D(int _n, int _m) : n(_n), m(_m) {
f.assign(n, vector<T>(m, T{}));
}
// O(n*m) Construction
FenwickTree2D(const vector<vector<T>>& v) {
n = v.size();
m = v[0].size();
f.assign(v.begin(), v.end());
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
int r = j | (j + 1);
if (r < m) {
f[i][r] += f[i][j];
}
}
}
for (int j = 0; j < m; j++) {
for (int i = 0; i < n; i++) {
int r = i | (i + 1);
if (r < n) {
f[r][j] += f[i][j];
}
}
}
}
void add(int x, int y, const T& v) {
assert(x >= 0 && x < n);
assert(y >= 0 && y < m);
for (int i = x; i < n; i = i | (i + 1)) {
for (int j = y; j < m; j = j | (j + 1)) {
f[i][j] += v;
}
}
}
T get(int x, int y) const {
T res{};
for (int i = x; i >= 0; i = (i & (i + 1)) - 1) {
for (int j = y; j >= 0; j = (j & (j + 1)) - 1) {
res += f[i][j];
}
}
return res;
}
T get(int l1, int r1, int l2, int r2) const {
assert(l1 >= 0 && l1 <= r1 && r1 < n);
assert(l2 >= 0 && l2 <= r2 && r2 < m);
l1--, l2--;
return get(r1, r2) - get(l1, r2) - get(r1, l2) + get(l1, l2);
}
};
void solve() {
int n, q;
cin >> n >> q;
vector a(n, vector<int>(n));
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
cin >> a[i][j];
}
}
FenwickTree2D<int> fen(a);
while (q--) {
int op;
cin >> op;
if (op == 1) {
int x, y, v;
cin >> x >> y >> v;
x--, y--;
fen.add(x, y, v);
} else if (op == 2) {
int l1, r1, l2, r2;
cin >> l1 >> r1 >> l2 >> r2;
l1--, r1--, l2--, r2--;
cout << fen.get(l1, r1, l2, r2) << '\n';
}
}
}
int32_t main() {
ios_base::sync_with_stdio(false);
cin.tie(nullptr);
int t = 1;
//cin >> t;
while (t--) {
solve();
}
return 0;
}