-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfenwick_tree.cpp
More file actions
46 lines (44 loc) · 977 Bytes
/
fenwick_tree.cpp
File metadata and controls
46 lines (44 loc) · 977 Bytes
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
#include<bits/stdc++.h>
using namespace std;
int getSum(int BITree[], int index)
{
int sum = 0; // Iniialize result
index = index + 1;
while (index>0)
{
sum += BITree[index];
index -= index & (-index);
}
return sum;
}
void updateBIT(int BITree[], int n, int index, int val)
{
index = index + 1;
while (index <= n)
{
BITree[index] += val;
index += index & (-index);
}
}
int *constructBITree(int arr[], int n)
{
int *BITree = new int[n+1];
for (int i=1; i<=n; i++)
BITree[i] = 0;
for (int i=0; i<n; i++)
updateBIT(BITree, n, i, arr[i]);
return BITree;
}
int main()
{
int freq[] = {2, 1, 1, 3, 2, 3, 4, 5, 6, 7, 8, 9};
int n = sizeof(freq)/sizeof(freq[0]);
int *BITree = constructBITree(freq, n);
cout << "Sum of elements in arr[0..5] is "
<< getSum(BITree, 5);
freq[3] += 6;
updateBIT(BITree, n, 3, 6);
cout << "\nSum of elements in arr[0..5] after update is "
<< getSum(BITree, 5);
return 0;
}