Skip to content

Commit d403a0e

Browse files
committed
Added Fenwick tree aka Binary indexed tree, used for dynamic sum queries.
1 parent 9f4da40 commit d403a0e

File tree

1 file changed

+33
-0
lines changed

1 file changed

+33
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
#include <bits/stdc++.h>
2+
using namespace std;
3+
4+
// BIT[] is 1-based indexed, hence size = n + 1.
5+
6+
const int n = 5;
7+
8+
int BIT[n + 1];
9+
10+
void update(int x, int delta) // add delta at index x
11+
{
12+
for (; x <= n; x += x &-x)
13+
BIT[x] += delta; // update sum value at all indices which cover x
14+
}
15+
16+
int query(int x)
17+
{
18+
int sum = 0;
19+
for (; x > 0; x -= x&-x)
20+
sum += BIT[x];
21+
return sum;
22+
}
23+
24+
int main()
25+
{
26+
int a[] = {1, 2, 3, 4, 5};
27+
for (int i = 0; i < n; i++)
28+
{
29+
update(i + 1, a[i]);
30+
}
31+
cout << "sum i, 1 to 3: " << query(4) - query(1) << "\n";
32+
return 0;
33+
}

0 commit comments

Comments
 (0)