https://www.geeksforgeeks.org/binary-indexed-tree-or-fenwick-tree-2/
#include <bits/stdc++.h> # define LL long long using namespace std; void updateTree(int BITree[], int index, int n,int val){ index++; while(index<=n){ BITree[index]+=val; index+=index&(-index); } } int* constructTree(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){ updateTree(BITree,i,n,arr[i]); } return BITree; } int getSum(int BITree[], int index){ index++; int res=0; while(index>0){ res+=BITree[index]; index-=index&(-index); } return res; } 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=constructTree(freq,n); int sum=getSum(BITree,5); cout<<"the sum from 0 to 5 is "<<sum<<" "; freq[3]+=6; updateTree(BITree,3,n,6); sum=getSum(BITree,5); cout<<"after update, the sum is "<<sum<<" "; return 0; }