Graph Theory37 sections · 1633 units
Open in Course

Problem - Distance Queries

(CSES 1135)

You are given a tree with nn nodes and qq queries. Each query asks for the distance between two nodes. Since qq can be large (up to 200,000200,000), you want O(1)O(1) queries. Use Euler tour + sparse table for LCA, then apply the distance formula. Preprocess: run DFS to compute depths, build Euler tour, build sparse table.

For each query (u, v), find lca(u, v) in O(1)O(1), then compute depth[u] + depth[v] - 2 * depth[lca] in O(1)O(1). Total time: O(nlogn+q)O(n \log n + q). This is fast enough for the problem constraints. The insight is recognizing that distance queries reduce to LCA queries.