- Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfenwick_tree.cpp
More file actions
Latest commit
35 lines (29 loc) · 684 Bytes
/
Copy pathfenwick_tree.cpp
File metadata and controls
35 lines (29 loc) · 684 Bytes
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
#include<vector>
usingnamespacestd;
// Fenwick Tree (Binary Indexed Tree)
// 1-indexed 구현
structFenwickTree {
int n;
vector<longlong> tree;
FenwickTree(int n) : n(n) { tree.resize(n + 1); }
// idx에 val 더하기 (point update)
voidupdate(int idx, longlong val) {
while (idx <= n) {
tree[idx] += val;
idx += (idx & -idx);
}
}
// 1 ~ idx 구간 합 (prefix sum)
longlongquery(int idx) {
longlong sum = 0;
while (idx > 0) {
sum += tree[idx];
idx -= (idx & -idx);
}
return sum;
}
// left ~ right 구간 합
longlongquery(int left, int right) {
returnquery(right) - query(left - 1);
}
};