Fenwick tree

Fenwick tree (aka Binary indexed tree) is a data structure that maintains a sequence of elements, and is able to compute cumulative sum of any range of consecutive elements in $$O(\log n)$$ time. Changing value of any single element needs $$O(\log n)$$ time as well.

The structure is space-efficient in the sense that it needs the same amount of storage as just a simple array of $$n$$ elements.

Sample C++ Implementation
using namespace std;
 * 1) include

// In this implementation, the tree is represented by a vector. // Elements are numbered by 0, 1, ..., n-1. // tree[i] is sum of elements with indexes i&(i+1)..i, inclusive. // (Note: this is a bit different from what is proposed in Fenwick's article. // To see why it makes sense, think about the trailing 1's in binary // representation of indexes.)

// Creates a zero-initialized Fenwick tree for n elements. vector create(int n) { return vector (n, 0); }

// Returns sum of elements with indexes a..b, inclusive int query(const vector &tree, int a, int b) { if (a == 0) { int sum = 0; for (b >= 0; b = (b & (b + 1)) - 1) sum += tree[b]; return sum; } else { return query(tree, 0, b) - query(tree, 0, a-1); } }

// Increases value of k-th element by inc. void increase(vector &tree, int k, int inc) { for (k < (int)tree.size; k |= k + 1) tree[k] += inc; }