-
Notifications
You must be signed in to change notification settings - Fork 30
Expand file tree
/
Copy pathfenwick_tree.cpp
More file actions
40 lines (37 loc) · 848 Bytes
/
fenwick_tree.cpp
File metadata and controls
40 lines (37 loc) · 848 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
36
37
38
39
40
const int N = (1 << 17);
// Binary Indexed Tree (i.e Fenwick Tree).
// Do not access this array directly.
int BIT[N];
/**
* Updates an element in the Fenwick tree.
* Note that the tree is 1-indexed.
*
* Complexity: O(log(N))
*
* @param idx the index of the element to be updated.
* @param val the value to add to the given element.
*/
void update(int idx, int val) {
while (idx < N) {
BIT[idx] += val;
idx += idx & -idx;
}
}
/**
* Computes the prefix sum of values in the Fenwick tree.
* Note that the tree is 1-indexed.
*
* Complexity: O(log(N))
*
* @param idx the index of the last element in the prefix sum.
*
* @return the sum of values in interval [1, idx].
*/
int get(int idx) {
int res = 0;
while (idx > 0) {
res += BIT[idx];
idx -= idx & -idx;
}
return res;
}