-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBinaryIndexedTree.cpp
More file actions
61 lines (53 loc) · 1.12 KB
/
Copy pathBinaryIndexedTree.cpp
File metadata and controls
61 lines (53 loc) · 1.12 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
48
49
50
51
52
53
54
55
56
57
58
59
60
61
/**
* Author: Kevin Li
* Lang: C++
* Description: Binary Indexed Tree for range sum, or Fenwick tree
*/
#include <iostream>
#include <vector>
using namespace std;
#define pb push_back
template<class T>
struct bit {
int n;
vector<T> b;
bit () {}
bit (int _n) : n(_n) {
b.clear();
for (int i = 0; i < n+1; i++) b.pb(0);
}
void adjust(int index, T value) {
for (int i = index; i <= n; i += ((i) & (-i))) {
b[i] += value;
}
}
T rsq(int l, int r) {
T sl = 0, sr = 0;
for (; l; l -= ((l)&(-l))) {
sl += b[l];
}
for (; r; r -= ((r)&(-r))) {
sr += b[r];
}
return sr - sl;
}
void construct(vector<T> a) {
n = (int)a.size();
b.clear();
for (int i = 0; i < n+1; i++) b.pb(0);
for (int i = 1; i <= n; i++) {
adjust(i,a[i-1]);
}
}
};
int n;
vector<int> a;
int main() {
cin >> n;
for (int i = 0; i < n; i++) {
int v; cin >> v;
a.pb(v);
}
bit<int> BIT = bit<int>();
BIT.construct(a);
}