Skip to content

Commit 5269330

Browse files
Add Fenwick Tree algorithm - Gabriel123Duarte
1 parent cd47f96 commit 5269330

File tree

2 files changed

+60
-0
lines changed

2 files changed

+60
-0
lines changed

include/fenwick_tree.h

Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
#ifndef __FENWICK_H__
2+
#define __FENWICK_H__
3+
4+
#include <vector>
5+
6+
#define LSONE(x) (x & (-x))
7+
8+
class Fenwick
9+
{
10+
private:
11+
std::vector<int> fen;
12+
public:
13+
Fenwick() {}
14+
15+
// We don't use the index 0
16+
Fenwick(int n)
17+
{
18+
fen.assign(n + 1, 0);
19+
}
20+
21+
// RSQ 1..a
22+
int rsq(int a)
23+
{
24+
int ans = 0;
25+
for(; a; a -= LSONE(a))
26+
ans += fen[a];
27+
return ans;
28+
}
29+
30+
// RSQ a..b
31+
inline int rsq(int a, int b)
32+
{
33+
return rsq(b) - (a == 1 ? 0 : rsq(a - 1));
34+
}
35+
36+
// Update the value of the k-th element by x
37+
void update(int k, int x)
38+
{
39+
for(; k < (int)fen.size(); k += LSONE(k))
40+
fen[k] += x;
41+
}
42+
};
43+
44+
#endif

src/fenwick_tree_demo.cpp

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
#include <cstdio>
2+
#include "fenwick_tree.h"
3+
4+
int main()
5+
{
6+
Fenwick ft(5);
7+
8+
ft.update(2, 1);
9+
ft.update(4, 10);
10+
11+
printf("%d\n", ft.rsq(1));
12+
13+
ft.update(1, 5);
14+
printf("%d\n", ft.rsq(1));
15+
return 0;
16+
}

0 commit comments

Comments
 (0)