-
Notifications
You must be signed in to change notification settings - Fork 80
/
FenwickTree.cpp
64 lines (56 loc) · 1.03 KB
/
FenwickTree.cpp
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
template <typename T>
class fenwick { // 1-based indexing (keep 0-based in main)
public:
T size;
vector<T > table;
fenwick(T size) {
this->size = size+1;
table.assign(size+1, 0);
}
fenwick(vector<T > a) : fenwick(a.size()) {
for (size_t i = 0; i < a.size(); i++) {
addin(i, a[i]);
}
}
void addin(T i, T data) {
for (++i; i < size; i += i & -i) {
table[i] += data;
}
}
// Update ith value by delta
void update(T i, T delta) {
while (i < size) {
table[i] += delta;
i += (i & -i);
}
}
// Update l to r inclusive values ny delta
void update(T l, T r, T delta) {
addin(l, delta);
addin(r+1, -delta);
}
void change(T i, T change) {
T prevdata;
if(i<size) {
prevdata = table[i];
table[i]=change;
}
T delta=change - prevdata;
update(i, delta);
}
// Compute prefix sum from 1 to i
T sum(T i) {
T sum = 0;
while (i > 0) {
sum += table[i];
i -= (i & -i);
}
return sum;
}
T rangesum(T l, T r) {
return sum(r) - sum(l-1);
}
/* In main()
1. fenwick<int> bit(a);
*/
};