forked from ccgcv/Cplus-plus-for-hacktoberfest
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathFenwick_Tree.cpp
More file actions
58 lines (41 loc) · 949 Bytes
/
Fenwick_Tree.cpp
File metadata and controls
58 lines (41 loc) · 949 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
47
48
49
50
51
52
53
54
55
56
57
58
#include <iostream>
using namespace std;
int getSum(int BITree[], int index)
{
int sum = 0;
index = index + 1;
while (index > 0)
{
sum += BITree[index];
index -= index & (-index);
// index = index & (index-1);
}
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[] = {10, 20, 30, 40, 50, 60, 70, 80, 90};
int n = sizeof(freq) / sizeof(freq[0]);
int *BITree = constructBITree(freq, n);
cout << "Sum of elements in arr[0..5] is "
<< getSum(BITree, 5);
return 0;
}