a =suma[0:8]F[8]a[0:4]F[4]1t[v] = t[2*v] + t[2*v+1]2i -= i & -i3i += i & -ia[0:2]F[2]a[4:8]a[2:4]a[0]5F[1]a[4:6]F[6]a[1]8a[2]6F[3]a[6:8]a[3]3a[4]2F[5]a[5]7a[6]2F[7]a[7]6586327261399822178992+4+4+421322+3+3
Cells: one node each, its slice of a on the front and the sum it storesLines on the table: parent to childA flying chip: a value moving from one node to anotherA segment tree over a = [5, 8, 6, 3, 2, 7, 2, 6]: each cell stores the sum of the slice printed on its front, and a parent is the sum of its two children. A range sum adds a few whole cells; a change fixes the cells on one path to the root. Both cost O(log n). The Fenwick tree keeps only the root and the left children, n cells in a list F[1..n], and walks it with i -= i & -i and i += i & -i.

The problem

  1. The list a holds 8 numbers. We want sums of slices, like sum(a[1:7]), while values keep changing. Adding up a slice costs O(n) every time. Prefix sums answer in O(1), but one change can rewrite n of them.

Segment trees

Fenwick trees

Choosing

What happens

;; step 1/10 · range-sums
a = [5, 8, 6, 3, 2, 7, 2, 6]
sum(a[1:7]) = 8 + 6 + 3 + 2 + 7 + 2 = 28

a[l:r] means items l, l + 1, ..., r - 1
loop over the slice:  query O(n), change O(1)
prefix sums:          query O(1), change O(n)
goal:                 both O(log n)

The segment tree here is stored like a heap: the root is t[1] and node v has children 2v and 2v + 1, so the leaves t[n..2n − 1] are a itself. That needs n to be a power of two; for other n, pad a with zeros, or use the recursive version in Sedgewick and Wayne's SegmentTree.java. Why at most two whole nodes per level: the nodes a query takes on one level are side by side, and two side-by-side nodes with the same parent would have been taken as that parent instead. So only the two ends of the slice can need a node at each level. The tests check every one of the 36 slices of a.