Graph Theory37 sections · 1633 units
Open in Course

Algorithm

(Class-based binary lifting)

Constructor:

1.1. Store nn and parent array.

2.2. Compute LOG=log2nLOG = \lceil \log_2 n \rceil.

3.3. Build up[n][LOG]:

up[i][0] = parent[i]

up[i][j] = up[up[i][j-1]][j-1]

getKthAncestor(node,k)getKthAncestor(node, k):

1.1. For j=0j = 0 to LOG1LOG-1, if k&(k \& (1j) \ll j), set node = up[node][j].

2.2. If node becomes 1-1, return 1-1.

3.3. Return node.

This runs in O(nlogn)O(n \log n) time and uses O(nlogn)O(n \log n) space.