#472 · Trees · Expert · 240 XP · about 45 min
n villages, numbered 0 to n - 1, are joined by the n - 1 footpaths in paths, each a pair [a, b], so that there is exactly one way between any two villages: the map is a tree. The distance between two villages is the number of footpaths on the way between them.
Write sum_of_distances(n, paths) that returns a list whose item i is the total of the distances from village i to every other village.
sum_of_distances(4, [[0, 1], [1, 2], [1, 3]]) # returns [5, 3, 5, 5] sum_of_distances(3, [[0, 1], [1, 2]]) # returns [3, 2, 3] sum_of_distances(1, []) # returns [0]
In the first map, village 1 is next to all the others (1 + 1 + 1 = 3), while from village 0 the others are 1, 2 and 2 footpaths away, a total of 5.
1 <= n <= 30,000, and the footpaths always form a tree.First solves only, ranked by stars and then time.