Fenwick Tree
A tiny structure that keeps prefix sums up to date while values change: both updating and querying cost only about log n steps.
After this lesson you will be able to
- Explain the problem a Fenwick tree solves, and why a prefix-sum array cannot handle changing data.
- Read and use lowbit (
i & -i), and trace which cells a query and an update touch. - Implement point update, prefix query and range query in a few lines.
- Build a Fenwick tree in O(n) and convert “set a value” into “add a difference”.
- Use a Fenwick tree with coordinate compression to count inversions, and know its limits (invertible operations only).
Before you start. Prefix Sum is essential. Comfort with binary numbers helps: you will use the lowest set bit of an index.