Graph Theory37 sections · 1633 units
Open in Course

Problem - Tree Distances II (CSES 1133)

(CSES problem)

Here is your first rerooting problem. Given a tree of nn nodes, compute the sum of distances from each node to all other nodes. The distance between two nodes is the number of edges on the path between them.

Input: first line is nn. Next n1n - 1 lines each have two integers aa and bb describing an edge. Output: nn integers, where the ii-th integer is the sum of distances from node ii to every other node.

Brute force runs a BFS from each node in O(n2)O(n^2). You need O(n)O(n) using rerooting. Think about what changes when you shift the root from uu to child vv.