Help chop every leaf off a bonsai tree.
You are given an undirected tree (a connected graph with no cycles) on n vertices. Each edge (a branch) has a nonnegative integer weight (its thickness). One vertex r 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 r — 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.
The input contains several test cases.
Each test case starts with a line holding two integers n and r (1≤n≤1000, 1≤r≤n): the number of vertices and the index of the root.
The next n−1 lines each hold three integers ui vi wi (1≤ui,vi≤n, 0≤wi≤1000), meaning there is an undirected edge of weight wi between vertices ui and vi. 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.
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.