-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathFenwick.cc
More file actions
54 lines (47 loc) · 1.25 KB
/
Fenwick.cc
File metadata and controls
54 lines (47 loc) · 1.25 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
#include <bits/stdc++.h>
using namespace std;
using VI = vector<int>;
using VVI = vector<VI>;
const int INF = 1e9;
/*Fenwick tree
* El Fenwick tree es una estructura para calcular y manipular "prefix sums"
* apartir de una estructura de arbol binario
* Puedes consultar:
* -la suma de [1,b] --> suma de [a,b] esta indexado en 1
* -puedes aumentar el valor k-esimo
* -puedes multiplicar todos los elementos por k
* Complejidad O(logn) para consultar y actualizar
* Complejidad O(N) multiplicar
*/
struct Fenwick{
int n; //Size of array
vector<int> tree;
void Build(const vector<int>& v, int m){ //Initializes the tree
n = m+1;
tree = vector<int>(n,0);
for(int i = 0; i < m; ++i){
update(i,v[i]);
}
}
//all queries are 0-indexed
int read(int idx){ //Gives the sum [1,idx]
int sum = 0;
idx++;
while (idx > 0){
sum += tree[idx];
idx -= (idx & -idx);
}
return sum;
}
void update(int idx,int val){ //Increases the k-th value
idx++;
while (idx < n){
tree[idx] += val;
idx += (idx & -idx);
}
}
void scale(int c){ //multiplies all numbers by a c factor
for (int i = 1 ; i < n ; i++)
tree[i] = tree[i] * c;
}
};