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.zig
const std = @import("std");

fn show(value: i64) !void {
    var buffer: [64]u8 = undefined;
    var writer = std.fs.File.stdout().writer(&buffer);
    try writer.interface.print("{d}\n", .{value});
    try writer.interface.flush();
}

pub fn main() !void {
    var tree = [_]i64{0, 0, 0, 0, 3, 8, 5, 2};
    var node: i64 = 3;
    while (node > 0) {
        const left: i64 = tree[@intCast((node * 2))];
        const right: i64 = tree[@intCast(((node * 2) + 1))];
        tree[@intCast(node)] = left;
        if (right > left) {
            tree[@intCast(node)] = right;
        }
        node -= 1;
    }
    try show(tree[1]);
}
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).