Skip to content

Instantly share code, notes, and snippets.

@istepura
Created July 22, 2014 08:25
Show Gist options
  • Save istepura/d5c1d5e98138dd390108 to your computer and use it in GitHub Desktop.
Save istepura/d5c1d5e98138dd390108 to your computer and use it in GitHub Desktop.
Simple Fenwick (binary indexed tree) tree implementation
#define MAXSZ 200001
int sum[MAXSZ];
inline void init(int sz){
fill_n(sum, sz + 1, 0);
}
inline void update(int* arr, int sz, int idx, int val)
{
while(idx <= sz){
arr[idx] += val;
idx += (idx & -idx);
}
}
inline int prefixsum(int* arr, int idx){
auto sum = 0;
while (idx> 0){
sum += arr[idx];
idx -= (idx & -idx);
}
return sum;
}
inline int query(int* arr, int l, int r){
return prefixsum(arr, r) - ((l > 1) ? prefixsum(arr, l - 1) : 0);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment