Graph Theory37 sections · 1633 units
Open in Course

Sparse Table Idea

(Store power-of-2 ancestors)

Define up[v][j] = the 2j2^j-th ancestor of node vv. This is the node you reach by jumping up 2j2^j steps from vv. For example, up[v][0] is the parent (jump 20=12^0 = 1 step). up[v][1] is the grandparent (jump 21=22^1 = 2 steps). up[v][3] is the 88th ancestor.

If you precompute this table, you can answer any kk-th ancestor query by decomposing kk into powers of 22 and making at most logk\log k jumps.