Roasting Emma is a barista too
InterviewTime limit1.5sMemory limit128 MB
Given a weighted tree, compute for every vertex the sum of shortest distances to all other vertices.
- Level
Medium5 of 10
- Topics
- Tree, DFS, Dynamic programming, Prefix sum
- Solved
- No attempts yet
Problem
Emma roasts coffee beans and works as a barista. She has linked her farms into a tree with vertices, and the farms are numbered 1 through . Each edge means you can travel between those two farms, and the weight of an edge is the travel distance.
Emma wants to pick one farm and set up a roasting facility next to it. To place it well she needs to know how far the other farms are from the facility in total. For every farm, find the sum of the shortest distances from all the other farms to that farm.
Input
The first line contains . ()
Each of the next lines contains three integers , , and . Farm and farm are connected to each other and the distance between them is . (, )
The given graph is a tree.
Output
Print lines. Line contains the sum of the shortest distances from all the other farms to farm .