Fenwick Tree
A Fenwick/Binary-Indexed tree can both process range sum queries and update values real-time in .
I still don’t fully grasp why it works, but I grasp the algorithm.
To process a query, we use this formula: which gets the rightmost set bit of .
- Add to a running sum
- Decrement by , which subtracts its rightmost set bit
- Repeat until reaches 0
- Return the running sum
To update a value at index i, we only update certain indices of the tree:
- Update
- Increment by
- Repeat until is out of bounds, i.e. while
Implementation (1-indexed)
This is the default implementation that supports range queries and point updates.
int sum(int k) {
int s = 0;
while (k > 0) {
s += tree[k];
k -= k&-k;
}
return s;
}
int range_sum(int l, int r) {
return sum(r) - sum(l-1);
}
void update(int i, int x) {
while (i <= n) {
tree[i] += x;
i += i&-i;
}
}
Variants (to master)
The following are variants of Fenwick trees that need extra work.
- Point Update and Range Query (Default)
- Range Update and Point Query
- Range Update and Range Query
Extra
This below is confusing to me, but I think it’s still good information. Each value of corresponds to