Skip to content

Commit

Permalink
Create Fenwick-Tree-Range-Sum.cpp
Browse files Browse the repository at this point in the history
  • Loading branch information
cppnuts-yt committed Dec 9, 2016
1 parent 4f78275 commit b6999cb
Showing 1 changed file with 36 additions and 0 deletions.
36 changes: 36 additions & 0 deletions Fenwick-Tree-Range-Sum.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
#include <bits/stdc++.h>
using namespace std;

void update(int BIT[], int x, int val, int n) {
for(; x<=n; x+=x&(-x)){
BIT[x]+=val;
}
}

int query(int BIT[], int x) {
int sum=0;
for(; x>0; x-=x&(-x)) {
sum+=BIT[x];
}
return sum;
}

int main() {
int N, Q, range;

cin >> N;
int arr[N+1];
int *BIT = (int*)calloc(N+1,sizeof(int));;

for(int i=1; i<N+1; ++i) {
cin >> arr[i];
update(BIT, i, arr[i], N);
}
cin >> Q; // number of query

while(Q--) {
cin >> range;
cout << query(BIT,range) << endl;
}
return 0;
}

0 comments on commit b6999cb

Please sign in to comment.