-
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 (46 loc) · 960 Bytes
/
binary_indexed_tree.cpp
File metadata and controls
47 lines (46 loc) · 960 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
#include <bits/stdc++.h>
using namespace std;
class binary_indexed_tree{
private:
int* bit;
int* vals;
int N;
int lsb(int x){
return x&(-x);
}
int prefix(int i){
//prefix of first i
int sum = 0;
while(i > 0){
sum += bit[i];
i -= lsb(i);
}
return sum;
}
public:
binary_indexed_tree(int sz, int* initial){
N = sz;
bit = new int[N+1];
vals = initial;
for(int i = 1; i <= N; i++){
bit[i] = accumulate(vals+i-lsb(i), vals+i, 0);
}
}
~binary_indexed_tree(){
delete[] bit, delete[] vals;
}
int query(int a, int b){
//[a, b)
return prefix(b) - prefix(a);
}
void set(int i, int k){
update(i, k-vals[i]);
}
void update(int i, int k){
vals[i++] = k;
while(i <= N){
bit[i] += k;
i += lsb(i);
}
}
};