Problem 699
Sum of Distances in Tree
Hard · 30 pts · Tree, Depth-First Search, Dynamic Programming
Problem
A tree has N nodes numbered from 1 to N. For every node, compute the sum of its distances (numbers of edges) to all other nodes. Running a search from every node takes O(N²). Instead, root the tree at node 1 and compute subtree sizes and the answer for the root with one pass. Then move the root across each edge: going from a parent p to a child c, answer(c) = answer(p) - size(c) + (N - size(c)).
Input
The first line contains N and M = N - 1. Each of the next N - 1 lines contains an edge u v.
Output
Print N integers separated by spaces: the distance sum for nodes 1 to N.
Constraints
1 <= N <= 30000; the edges form a tree
Example input
6 5 1 2 1 3 3 4 3 5 3 6
Example output
8 12 6 10 10 10
Explanation
In the tree with edges 1-2, 1-3, 3-4, 3-5 and 3-6, node 1 is at distance 1 from 2 and 3 and distance 2 from 4, 5 and 6, a total of 8. Doing the same for every node gives 8 12 6 10 10 10.