Segment Tree

The segment tree: range sum and point update in O(log n).

Prefix sums answer "sum on a segment" in O(1) but break as soon as the array starts CHANGING: one update — recompute all prefixes. The segment tree does both the query and the update in O(log n). The idea: build a binary tree over the array; each node stores the sum of its segment. The root — the sum of the whole array, the leaves — individual elements. • updating an element touches only the nodes on the path from the leaf to the root — O(log n) of them; • a query [l, r] decomposes into O(log n) ready-made tree segments.

Enter: 5 3, the array 1 2 3 4 5, then: sum 2 4 / set 3 10 / sum 2 4

Run the example: the sum of [2,4] is 9 at first, and after set 3 10 it becomes 16. How to read the code: • node v is responsible for the segment [tl, tr]; its children are the halves of the segment, numbered 2v and 2v+1; • the tree array of size 4n is guaranteed to fit the whole tree; • query returns 0 for non-overlapping segments — zero is neutral for the sum. The segment tree is a construction kit: replace + with min or max (and the neutral element with infinity) — and you get minimum/maximum queries. The advanced version with "lazy" updates can modify whole segments in O(log n) — study it when you meet such a problem.
Task: convert the tree to range MAXIMUM (three edits: the operation, the neutral element, the output) and test it on your own example. Mark the lesson as completed.
Доска