-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathBIT.cpp
111 lines (110 loc) · 2.55 KB
/
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
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
/// Fenwick tree, Point updates and range queries
int tree[N];
class Fenwick{
public:
int n;
Fenwick(){
}
Fenwick(int m){
n = m;
for (int i = 1; i <= n; i++) tree[i] = 0;
}
/// Add v to index p
void update(int p, int v){
while (p <= n){
tree[p] += v;
p += (p & (-p));
}
}
/// Returns sum from index [1:p]
int query(int p){
int res = 0;
while (p){
res += tree[p];
p ^= (p & (-p));
}
return res;
}
/// Returns sum from index [l:r]
int query(int l, int r){
if (l > r) return 0;
return (query(r) - query(--l));
}
};
/// Fenwick tree, Range updates and point queries
int tree[N];
class Fenwick{
public:
int n;
Fenwick(){
}
Fenwick(int m){
n = m;
for (int i = 1; i <= n; i++) tree[i] = 0;
}
/// Add v to index [p:n]
void update(int p, int v){
while (p <= n){
tree[p] += v;
p += (p & (-p));
}
}
/// Add v to index [l:r]
void update(int l, int r, int v){
if (l > r) return;
update(l, v);
update(r + 1, -v);
}
/// Returns value of index p
int query(int p){
int res = 0;
while (p){
res += tree[p];
p ^= (p & (-p));
}
return res;
}
};
/// Fenwick tree, Range updates and range queries
long long tree[N], temp[N];
class Fenwick{
public:
int n;
Fenwick(){
}
Fenwick(int m){
n = m;
for (int i = 1; i <= n; i++) tree[i] = temp[i] = 0;
}
void update(long long* tree, int p, long long v){
while (p <= n){
tree[p] += v;
p += (p & (-p));
}
}
/// Add v to index [l:r]
void update(int l, int r, long long v){
if (l > r) return;
update(tree, l, v);
update(tree, r + 1, -v);
update(temp, l, v * (l - 1));
update(temp, r + 1, (-v) * r);
}
long long query(long long* tree, int p){
long long res = 0;
while (p){
res += tree[p];
p ^= (p & (-p));
}
return res;
}
/// Returns sum from index [1:p]
long long query(int p){
return ((query(tree, p) * p) - query(temp, p));
}
/// Returns sum from index [l:r]
long long query(int l, int r){
if (l > r) return 0;
return (query(r) - query(--l));
}
};