This page is still under construction.

Parts of this page are still being built. What you see may change.

Central Tree

Interview

Time limit3sMemory limit128 MB

Summary
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 A,B,C,D,EA, B, C, D, E; the edges and their weights are:

  • B−AB - A : 2
  • B−CB - C : 1
  • B−DB - D : 7
  • D−ED - E : 5

Here the central vertex is BB. The distances from BB to each vertex are B→A=2,B→C=1,B→D=7,B→E=7+5=12B \to A = 2,\quad B \to C = 1,\quad B \to D = 7,\quad B \to E = 7 + 5 = 12 so their sum is 2+1+7+12=222 + 1 + 7 + 12 = 22.

Write a program that, even when the number of vertices NN 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 nn of the tree. (1≤n≤10,0001 \le n \le 10{,}000) The vertices are numbered from 00 to n−1n-1.

Each of the following n−1n-1 lines contains three integers aa, bb, and ww. (1≤w≤1001 \le w \le 100) This denotes an edge of weight ww connecting vertices aa and bb.

The last line of the input contains a single 00, 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).

Examples1

  1. Example 1

    Input
    5
    0 1 2
    1 2 1
    1 3 7
    3 4 5
    6
    0 1 1
    1 2 4
    2 3 1
    3 4 4
    4 5 1
    0
    
    Expected output
    22
    21