Central Tree
InterviewTime limit3sMemory limit128 MB
For each weighted tree, find the vertex minimizing the sum of weighted distances to all other vertices and output that minimum sum.
- Level
Medium7 of 10
- Topics
- Tree, DFS, Dynamic programming, Graph
- Solved
- No attempts yet
Problem
A tree is a connected graph with no cycles.
Call a vertex a central vertex if the sum of the (weighted) distances from it to every other vertex is as small as possible. When the number of vertices is small, you can find it easily by trying every vertex one by one.
For example, consider the following tree with 5 vertices. Name the vertices ; the edges and their weights are:
- : 2
- : 1
- : 7
- : 5
Here the central vertex is . The distances from to each vertex are so their sum is .
Write a program that, even when the number of vertices is large, reads a tree and computes the sum of the distances from every vertex to the central vertex (that is, the minimum possible sum defined above).
Input
The input consists of several test cases. The first line of each test case contains the number of vertices of the tree. () The vertices are numbered from to .
Each of the following lines contains three integers , , and . () This denotes an edge of weight connecting vertices and .
The last line of the input contains a single , marking the end of the input.
Output
For each test case, print on its own line the sum of the distances from every vertex to the central vertex (the minimum possible sum).