-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathFenwick_Tree_2D_Range_Update_Point_Query.cpp
More file actions
114 lines (104 loc) · 2.8 KB
/
Fenwick_Tree_2D_Range_Update_Point_Query.cpp
File metadata and controls
114 lines (104 loc) · 2.8 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
106
107
108
109
110
111
112
113
114
#include <bits/stdc++.h>
using namespace std;
// Range Update & Point 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(n, vector<T>(m, T{}));
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
T up = (i > 0) ? v[i - 1][j] : T{};
T left = (j > 0) ? v[i][j - 1] : T{};
T corner = (i > 0 && j > 0) ? v[i - 1][j - 1] : T{};
f[i][j] = v[i][j] - up - left + corner;
}
}
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) {
for (int i = x; i < n; i = i | (i + 1)) {
for (int j = y; j < m; j = j | (j + 1)) {
f[i][j] += v;
}
}
}
void add(int l1, int r1, int l2, int r2, const T& v) {
assert(l1 >= 0 && l1 <= r1 && r1 < n);
assert(l2 >= 0 && l2 <= r2 && r2 < m);
add(l1, l2, v);
add(l1, r2 + 1, -v);
add(r1 + 1, l2, -v);
add(r1 + 1, r2 + 1, v);
}
T get(int x, int y) const {
assert(x >= 0 && x < n);
assert(y >= 0 && y < m);
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;
}
};
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 l1, r1, l2, r2, v;
cin >> l1 >> r1 >> l2 >> r2 >> v;
l1--, r1--, l2--, r2--;
fen.add(l1, r1, l2, r2, v);
} else if (op == 2) {
int x, y;
cin >> x >> y;
x--, y--;
cout << fen.get(x, y) << '\n';
}
}
}
int32_t main() {
ios_base::sync_with_stdio(false);
cin.tie(nullptr);
int t = 1;
//cin >> t;
while (t--) {
solve();
}
return 0;
}