Graph Theory37 sections · 1633 units
Open in Course

Algorithm

(Full tour plus RMQ)

1.1. Run DFS recording full tour: add vv when entering and when returning from each child.

2.2. Store depth of each node in the tour.

3.3. Record first[v] = first position of vv in the tour.

4.4. Build RMQ structure on the depth array (sparse table for O(1)O(1) query or segment tree for O(logn)O(\log n)).

5.5. For LCA(uu, vv): query RMQ on range [min(first[u], first[v]), max(first[u], first[v])], return node at the position with minimum depth. Preprocessing: O(nlogn)O(n \log n). Query: O(1)O(1) with sparse table or O(logn)O(\log n) with segment tree.

Space complexity is O(n)O(n) for the data structures used.