Data Structures19 sections · 729 units
Open in Course

Problem - Distance Queries

Classic centroid problem

Given a tree with nn nodes and qq queries, answer distance queries: what is the distance (number of edges) between nodes uu and vv? Constraints: n,q2105n, q \leq 2 \cdot 10^5.

This you can solve with LCA, but centroid decomposition offers an alternative approach that extends to harder variants.

The idea: precompute distances from every node to all its centroid ancestors. Query (u,v)(u, v) finds their lowest common centroid ancestor and combines distances.