HDU 3452 Bonsai

Font Size:  

Problem Description

After being assaulted in the parking lot by Mr. Miyagi following the "All Valley Karate Tournament", John Kreese has come to you for assistance. Help John in his quest for justice by chopping off all the leaves from Mr. Miyagi's bonsai tree!
You are given an undirected tree (i.e., a connected graph with no cycles), where each edge (i.e., branch) has a nonnegative weight (i.e., thickness). One vertex of the tree has been designated the root of the tree.The remaining vertices of the tree each have unique paths to the root; non-root vertices which are not the successors of any other vertex on a path to the root are known as leaves.Determine the minimum weight set of edges that must be removed so that none of the leaves in the original tree are connected by some path to the root.

Input

The input file will contain multiple test cases. Each test case will begin with a line containing a pair of integers n (where 1 <= n <= 1000) and r (where r ∈ {1,……, n}) indicating the number of vertices in the tree and the index of the root vertex, respectively. The next n-1 lines each contain three integers u i v i w i (where u i, v i ∈ {1,……, n} and 0 <= w i <= 1000) indicating that vertex u i is connected to vertex v i by an undirected edge with weight w i. The input file will not contain duplicate edges. The end-of-file is denoted by a single line containing "0 0".

Output

For each input test case, print a single integer indicating the minimum total weight of edges that must be deleted in order to ensure that there exists no path from one of the original leaves to the root.

Sample 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

Sample Output

16


树形dp,要求最小的切割边使得所有叶子节点都不和根节点相连。


#include<iostream>
#include<cstdio>
#include<vector>
#include<algorithm>
#include<string>
#include<cstring>
#include<map>
using namespace std;
const int Maxn = 1005;
vector<int> tree[Maxn];
int n, x, y, z, dp[Maxn], root, c[Maxn][Maxn];

void work(int x, int fa, int ans)
{
	int tot = 0;
	for (int i = 0; i < tree[x].size(); i++)
	if (tree[x][i] != fa)
	{	
		int y = tree[x][i];
		work(y, x, c[x][y]);
		tot += dp[y];
	}
	dp[x] = tot ? min(tot, ans) : ans;
}

int main()
{
	while (~scanf("%d%d", &n, &root), n + root)
	{
		for (int i = 0; i <= n; i++) tree[i].clear();
		for (int i = 1; i < n; i++)
		{
			scanf("%d%d%d", &x, &y, &z);
			c[x][y] = c[y][x] = z;
			tree[x].push_back(y);
			tree[y].push_back(x);
		}
		work(root, root, 1 << 30);
		if (n == 1) cout << 0 << endl; 
		else cout << dp[root] << endl;
	}
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值