Graph Theory37 sections · 1633 units
Open in Course

Algorithm

(LCA with binary lifting)

1.1. Compute depth[v] for all nodes (BFS/DFS).\n\n2.2. Build the upup table.\n\n3.3. For query (a,b)(a, b): if depth[a] < depth[b], swap them.\n\n4.4. Jump aa up to the same depth as bb: jump depth[a] - depth[b] steps.\n\n5.5. If a=ba = b, return aa (one is ancestor of the other).\n\n6.6. Binary search: for j=lognj = \log n down to 00, if up[a][j] \!= up[b][j], jump both.\n\n7.7. Return up[a][0] (the LCA).\n\nThis runs in O(nlogn)O(n \log n) time and uses O(nlogn)O(n \log n) space.