-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbinary_indexed_tree.cpp
More file actions
55 lines (44 loc) · 1004 Bytes
/
binary_indexed_tree.cpp
File metadata and controls
55 lines (44 loc) · 1004 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
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
#include <bits/stdc++.h>
using namespace std;
#define int long long
struct BIT{
int max_size;
vector <int> bits;
BIT(int new_size){
max_size = new_size;
bits = vector <int> (new_size+1,0);
}
void increase(int x,int val){
int xx=x;
while(xx<=max_size){
bits[xx]+=val;
xx=xx+(xx&-xx);
}
}
int query(int pos){
int sum=0;
while(pos){
sum+=bits[pos];
pos=pos-(pos&-pos);
}
return sum;
}
};
int main(){
// Testing
cout<<"Testing BIT...\n";
BIT bit (6);
assert(bit.max_size + 1 == bit.bits.size());
bit.increase(4,5);
bit.increase(2,-3);
bit.increase(6,2);
assert(bit.query(0)==0);
assert(bit.query(1)==0);
assert(bit.query(2)==-3);
assert(bit.query(3)==-3);
assert(bit.query(4)==2);
assert(bit.query(5)==2);
assert(bit.query(6)==4);
cout<<"Testing passed!\n";
return 0;
}