Graph Theory37 sections · 1633 units
Open in Course

Planets Queries I - Implementation

(Binary lifting in code)

Here is the solution:

function preprocess(f, n)
    jump[0][x] := f[x] for all x
    for i from 1 to log2(n)
        for x from 1 to n
            jump[i][x] := jump[i-1][jump[i-1][x]]

function query(x, k)
    for i from log2(k) down to 0
        if k has bit i set then
            x := jump[i][x]
    return x

Time: O(nlogn)O(n \log n) preprocessing, O(logk)O(\log k) per query. Space: O(nlogn)O(n \log n) for the table. The bit manipulation checks each bit of kk to decide which jumps to make.