Graph Theory37 sections · 1633 units
Open in Course

Answering Queries

(Decompose k into powers)

To find the kk-th ancestor of vv, decompose kk into powers of 22. For each bit set in kk, make the corresponding jump.

For example, if k=13=11012k = 13 = 1101_2 (bits 00, 22, 33 are set), jump 202^0, then 222^2, then 232^3. That is three jumps total. After all jumps, you land at the kk-th ancestor. Time: O(logk)O(\log k) per query. If vv goes past the root during any jump, the ancestor does not exist. Return 1-1 in that case.