#include<iostream>
#include<vector>
#include<algorithm>
using namespace std;
class FenwickTree
{
//createTree: which fill the binaryIndexTree array where the required values are stored and manipulated;
//updateTree: which is used to insert of update a value of index 'i' from the source array which is done at index i+1 of the binaryIndexTree
//getSum : provide the sum upto a particular index of the array
//getParent: provide the parent of a index 'i';
//getNext: provides index of the childs and other nodes affected by changing an index 'i'
int* binaryIndexedTree=NULL;
int len = 0;
public:
FenwickTree(int arr[], int arrsize)
{
this->len = arrsize + 1;
cout << "len: " << len << endl;
this->binaryIndexedTree = new int[len];
createTree(arr);
}
void createTree(int arr[])
{
for(int i=0; i<len; i++) binaryIndexedTree[i] = 0;
binaryIndexedTree[0] = 0;
for(int i=1 ; i<len; i++)
{
updateTree(arr[i-1], i);
}
}
void updateTree(int value, int index)
{
cout << "Inside uptate";
while(index < len)
{
binaryIndexedTree[index] += value;
index = getNext(index);
}
}
//Step 1: Calculate 2's complement of index
//Step 2: DO Logical AND with the original index;
//Step 3 : Add the above got value with the original index
int getNext(int index)
{
return index + (index & -index);
}
//Step 1: Calculate 2's complement of index
//Step 2: DO Logical AND with the original index;
//Step 3 : Add the above got value with the original index
int getParent(int index)
{
return index - (index & -index);
}
int getSum(int index)
{
cout << "inside get sum";
index = index + 1;
int sum = 0;
while(index > 0)
{
sum += binaryIndexedTree[index];
index = getParent(index);
}
for(int i=0; i<len; i++) cout << binaryIndexedTree[i] << " ";
cout << endl;
return sum;
}
void updateTreeWithElement(int value, int index)
{
index = index + 1;
int diff_to_propagate = value - binaryIndexedTree[index];
while(index < len)
{
binaryIndexedTree[index] += diff_to_propagate;
index = getNext(index);
}
}
};
int main()
{
int input[] = {1,2,3,4,5,6,7};
FenwickTree* ft = new FenwickTree(input, sizeof(input)/sizeof(input[0]));
ft->updateTreeWithElement(6, 4);
ft->updateTreeWithElement(4, 4);
int ans = ft->getSum(5);
cout << "ans: " << ans << endl;
return 0;
}