-
Notifications
You must be signed in to change notification settings - Fork 16
/
binaryIndexTree.cpp
72 lines (64 loc) · 1.69 KB
/
binaryIndexTree.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
65
66
67
68
69
70
71
72
/**
Author: Sharique
email: shariqueshahab@gmail.com
Buid binary indexed tree using Array
Use case: Range queries
- finding sum from index i to j of an array.
operations:
- update -> log(n)
- read -> log(n)
Reference: https://www.topcoder.com/community/competitive-programming/tutorials/range-minimum-query-and-lowest-common-ancestor/
*/
#include <iostream>
#include<vector>
using namespace std;
class BinaryIndexTree {
vector<int> values;
vector<int> binaryIndexTree;
int maxIdx;
// build tree using updates
void build() {
for(int i = 0; i < values.size(); i++) {
update(values[i], i);
}
}
public:
BinaryIndexTree(vector<int> values) {
this -> values = values;
this -> binaryIndexTree.resize(values.size() + 1);
this -> maxIdx = binaryIndexTree.size();
build();
}
// update binaryIndexTree after update in original array at index idx
void update(int val, int idx) {
values[idx] = val;
idx++;
while(idx <= maxIdx) {
binaryIndexTree[idx] += val;
idx += (idx & -idx); // toggle last set bit
}
}
// returns sum from index 0 to idx
int read(int idx) {
int sum = 0;
while(idx > 0) {
sum += binaryIndexTree[idx];
idx -= (idx & -idx); // mark last set bit to zero
}
return sum;
}
// print tree stored in array
void show() {
for(int i : binaryIndexTree) cout<<i<<',';
cout<<endl;
}
};
int main() {
BinaryIndexTree tree(vector<int>{1,0,2,1,1,3,0,4,2,5,2,2,3,1,0,2});
cout<<"Sum of values from index 0 to index 13: "<< tree.read(13)<<endl;
tree.show();
tree.update(10,5);
cout<<"Sum of values from index 0 to index 13: "<< tree.read(13)<<endl;
tree.show();
return 0;
}