Lesson contents

Segment trees

Group adjacent items into intervals. Store a summary, such as a maximum, for each interval so a query can use whole groups.

Simple example

Build maxima for the pairs 3,8 and 5,2. Combine their maxima to print the maximum for the whole interval.

Start3 8 5 2
Result8
lesson.cpp
#include <iostream>

int main() {
    int tree[] = {0, 0, 0, 0, 3, 8, 5, 2};
    int node = 3;
    while (node > 0) {
        int left = tree[node * 2];
        int right = tree[(node * 2) + 1];
        tree[node] = left;
        if (right > left) {
            tree[node] = right;
        }
        node -= 1;
    }
    std::cout << tree[1] << '\n';
}
Output
8
Advertisements

Everyday examples

Find the warmest afternoon

Hourly readings are 16, 22, 19 and 18. Which reading wins over all four hours?

Start16 22 / 19 18
Result22

Compare the two pair maxima, 22 and 19, to get the overall maximum.

Correct one shelf count

Counts are 3, 8, 5 and 2. Replace 8 with 1. What is the new maximum?

Start3 1 / 5 2
Result5

Update the changed leaf, its pair maximum and the top maximum. The other pair stays valid.

Query a middle interval

Daily bookings are 7, 2, 6 and 9. What is the largest count on days two and three?

Start7 [2 6] 9
Result6

Use only intervals inside the requested days. Including day four would incorrectly return 9.

Cost and limits

An associative summary can be combined over intervals. A point update and a standard contiguous range query each take O(log n).