Skip to content

Commit 484bcf5

Browse files
committed
Added new data structure Fenwick Tree
Fenwick tree is data structure which is basically used to solve range query problems.
1 parent 6ba203d commit 484bcf5

File tree

1 file changed

+53
-0
lines changed

1 file changed

+53
-0
lines changed
+53
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,53 @@
1+
/*Let, f be some reversible function and A be an array of integers of length N.
2+
Fenwick tree is a data structure which:
3+
1.calculates the value of function f in the given range [l,r] (i.e. f(Al,Al+1,…,Ar)) in O(logn) time;
4+
2.updates the value of an element of A in O(logn) time;
5+
3.requires O(N) memory, or in other words, exactly the same memory required for A;
6+
4.is easy to use and code, especially, in the case of multidimensional arrays.
7+
Note:-
8+
Fenwick tree is also called Binary Indexed Tree, or just BIT .
9+
Application:-
10+
calculating the sum of a range (i.e. f(A1,A2,…,Ak)=A1+A2+⋯+Ak). */
11+
#include <bits/stdc++.h>
12+
using namespace std;
13+
14+
15+
int FNT[1000000] = {0}; //fenwick tree array
16+
int query(int i)
17+
{
18+
int ans = 0;
19+
while (i > 0)
20+
{
21+
ans += FNT[i];
22+
i = i - (i & (-i));
23+
}
24+
return ans;
25+
}
26+
void Build_update(int i, int inc, int N)
27+
{
28+
while (i <= N)
29+
{
30+
FNT[i] += inc;
31+
i += (i & (-i));
32+
}
33+
}
34+
int main()
35+
{
36+
37+
int n;
38+
cin >> n;
39+
int a[n];
40+
for (int i = 1; i <= n; i++)
41+
{
42+
cin >> a[i];
43+
Build_update(i, a[i], n);
44+
}
45+
int q, l, r;
46+
cin >> q;
47+
while (q--)
48+
{
49+
cin >> l >> r;
50+
cout << (query(r) - query(l - 1)) << endl;
51+
}
52+
return 0;
53+
}

0 commit comments

Comments
 (0)