-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbinary_indexed_tree.cpp
More file actions
63 lines (50 loc) · 1.03 KB
/
binary_indexed_tree.cpp
File metadata and controls
63 lines (50 loc) · 1.03 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
#include <cstdio>
#include <cassert>
#include <vector>
using namespace std;
typedef long long LL;
class BinIdxTree {
vector<LL> tree;
int sz; // 1 based indexed fenwick tree
public:
BinIdxTree(int n) {
sz = n;
tree.assign(n + 1, 0);
}
inline int offset(int x) {
return x & (-x);
}
void update(int idx, LL val)
{
while (idx <= sz) {
tree[idx] += val;
idx += offset(idx);
}
}
LL query(int idx) {
LL sum = 0;
while (idx > 0) {
sum += tree[idx];
idx -= offset(idx);
}
return sum;
}
};
int main()
{
int n = 10;
BinIdxTree bit = BinIdxTree(n);
int from = 5;
int to = 8;
long value = 100;
bit.update(from, value);
bit.update(to + 1, -value);
for (int i = 1; i <= n; ++i) {
if (from <= i && i <= to) {
assert(bit.query(i) == value);
} else {
assert(bit.query(i) == 0);
}
}
return 0;
}