-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbinary indexed tree.cpp
More file actions
47 lines (43 loc) · 1.02 KB
/
binary indexed tree.cpp
File metadata and controls
47 lines (43 loc) · 1.02 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
template <typename T>
struct BinaryIndexedTree {
vector<T> values;
vector<T> tree;
BinaryIndexedTree(int size) : values(size), tree(size) {}
BinaryIndexedTree(vector<T>& v) : values(v), tree(v.size() + 1) {
vector<T> temp = values;
for (int i = 0; i < values.size(); ++i) {
update(i, values[i]);
}
values = temp;
}
//return sum of values[0...index] inclusive
T prefix_sum(int index) {
T sum = 0;
index += 1;
while (index > 0) {
sum += tree[index];
//parent
index = index - (index & -index);
}
return sum;
}
void update(int index, T val) {
values[index] += val;
index += 1;
while (index <= values.size()) {
tree[index] += val;
index = index + (index & -index);
}
}
//returns sum of values[a...b], inclusive
T sum_between(int a, int b) {
if (a == 0)
return prefix_sum(b);
else if (b == 0)
return prefix_sum(a);
else if (a > b)
return prefix_sum(a) - prefix_sum(b - 1);
else
return prefix_sum(b) - prefix_sum(a - 1);
}
};