This page is still under construction.

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

Bonsai

Time limit1sMemory limit128 MB

Summary
Root a weighted tree and cut edges of minimum total weight so that no original leaf stays connected to the root.
Level

Medium6 of 10

Topics
Tree, DFS, Dynamic programming, Greedy
Solved
No attempts yet

Problem

Help chop every leaf off a bonsai tree.

You are given an undirected tree (a connected graph with no cycles) on nn vertices. Each edge (a branch) has a nonnegative integer weight (its thickness). One vertex rr is the root, and because the graph is a tree, every other vertex has a unique path to the root.

A leaf is a non-root vertex that has no children when the tree is rooted at rr — equivalently, a non-root vertex that is not the parent of any other vertex.

Determine the minimum total weight of edges that must be removed so that afterwards no leaf of the original tree is still connected to the root by any path.

Input

The input contains several test cases.

Each test case starts with a line holding two integers nn and rr (1≤n≤10001 \le n \le 1000, 1≤r≤n1 \le r \le n): the number of vertices and the index of the root.

The next n−1n-1 lines each hold three integers uiu_i viv_i wiw_i (1≤ui,vi≤n1 \le u_i, v_i \le n, 0≤wi≤10000 \le w_i \le 1000), meaning there is an undirected edge of weight wiw_i between vertices uiu_i and viv_i. No edge is listed twice, and the given edges always form a tree.

The input ends with a line containing 0 0, which is not a test case.

Output

For each test case, print a single line with one integer: the minimum total weight of edges that must be removed so that no original leaf is connected to the root.

Examples3

  1. Example 1

    Input
    15 15
    1 2 1
    2 3 2
    2 5 3
    5 6 7
    4 6 5
    6 7 4
    5 15 6
    15 10 11
    10 13 5
    13 14 4
    12 13 3
    9 10 8
    8 9 2
    9 11 3
    0 0
    
    Expected output
    16
    
  2. Example 2

    Input
    2 1
    1 2 5
    0 0
    
    Expected output
    5
    
  3. Example 3

    Input
    4 1
    1 2 5
    1 3 3
    1 4 8
    0 0
    
    Expected output
    16