-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathBIT.cpp
52 lines (43 loc) · 809 Bytes
/
BIT.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
#include <iostream>
using namespace std;
class BIT {
int *bit;
int N;
public:
void update(int x, int val) {
int ind = x;
while (ind <= N) {
bit[ind] += val;
ind += (ind & (-ind));
}
}
BIT(int ar[], int n) {
bit = new int[n+1];
N = n+1;
for (int i = 1; i < N; i++) bit[i] = 0;
for (int i = 1; i < N; i++) update(i, ar[i-1]);
}
int getSum(int x) {
if (x < 0) return 0;
int ind = x+1;
int sum = 0;
while (ind > 0) {
sum += bit[ind];
ind = (ind & (ind-1));
}
return sum;
}
int getValue(int x) {
return getSum(x) - getSum(x-1);
}
void changeElem(int x, int val) {
update(x+1, val-getValue(x));
}
};
int main() {
int ar[6] = {5, 1, -7, 3, -4, 6};
BIT b(ar, 6);
b.changeElem(4, 4);
for (int i=0; i < 6; i++) cout << b.getSum(i) << endl;
return 0;
}