Explanation
This problem asks us to find the lowest common ancestor (LCA) of two nodes in a tree. While this can be solved with binary lifting, we'll use Heavy-Light Decomposition (HLD) to practice the technique.
HLD Preprocessing:
- Compute subtree sizes to identify heavy children
- Decompose the tree into heavy paths
- Assign each node to a heavy path chain and store the top node
The key insight is that we can efficiently jump between heavy path chains when traversing from node to node . To find the LCA of two nodes:
- Repeatedly move the node with the deeper heavy path chain to its parent chain
- When both nodes are on the same heavy path chain, the node with smaller depth is the LCA
Any path passes through at most light edges and thus needs to jump through a max of heavy paths.
Implementation
Time Complexity:
C++
#include <algorithm>#include <iostream>#include <vector>using namespace std;const int N = 2e5 + 5;int n, q;vector<int> adj[N];
Join the USACO Forum!
Stuck on a problem, or don't understand a module? Join the USACO Forum and get help from other competitive programmers!