Fenwick Tree Implementation
To implement a Fenwick Tree, we need to create an array called BIT
(Binary Indexed Tree) which will store the values. The size of the BIT
array should be equal to the input array size plus one.
Here are the steps to implement a Fenwick Tree:
- Initialize the
BIT
array with zeros. - Update a value at an index:
- To update a value at a specific index, we need to iterate through all the affected indices in the
BIT
array and add the new value to each index. - The indices to be updated can be found by performing bitwise operations on the original index.
- Get the prefix sum up to a given index:
- To calculate the prefix sum up to a given index, we need to iterate through all the indices in the
BIT
array and sum up the values at each index. - The indices to be considered can be found by performing bitwise operations on the original index.
Here's an example implementation of the Fenwick Tree in C++:
SNIPPET
1#include <iostream>
2using namespace std;
3
4const int MAXN = 1000; // maximum array size
5
6// Fenwick Tree implementation
7
8void update(int BIT[], int index, int value) {
9 while (index <= MAXN) {
10 BIT[index] += value;
11 index += index & -index;
12 }
13}
14
15int getPrefixSum(int BIT[], int index) {
16 int sum = 0;
17 while (index > 0) {
18 sum += BIT[index];
19 index -= index & -index;
20 }
21 return sum;
22}
23
24int main() {
25 int arr[MAXN]; // original array
26 int BIT[MAXN + 1]; // Binary Indexed Tree
27
28 // Initialize BIT
29 for (int i = 1; i <= MAXN; i++) {
30 BIT[i] = 0;
31 }
32
33 // Update a value at index 5
34 int index = 5;
35 int value = 10;
36 update(BIT, index, value);
37
38 // Get prefix sum up to index 8
39 int prefixSum = getPrefixSum(BIT, 8);
40
41 cout << "Prefix Sum: " << prefixSum << endl;
42
43 return 0;
44}
xxxxxxxxxx
using namespace std;
int main() {
// Fenwick Tree implementation
// Replace with your C++ implementation here
return 0;
}
OUTPUT
:001 > Cmd/Ctrl-Enter to run, Cmd/Ctrl-/ to comment