Data Structures19 sections · 729 units
Open in Course

Distance Queries - Analysis

Using centroid ancestors

For each node vv, store dist[v][i]dist[v][i] = distance from vv to its ii-th centroid ancestor. Since centroid tree depth is O(logn)O(\log n), this takes O(nlogn)O(n \log n) space.

Query (u,v)(u, v): find the lowest centroid cc that is an ancestor of both uu and vv in the centroid tree.

Then: distance(u,v)=dist[u][c]+dist[v][c]distance(u, v) = dist[u][c] + dist[v][c] To find the common centroid ancestor, walk up from both uu and vv until you meet. With preprocessing, this takes O(logn)O(\log n) time.