HDU 3452 最小割 (树形dp)

来源:互联网 发布:下载农村淘宝免费下载 编辑:程序博客网 时间:2024/06/08 18:39


1、http://acm.hdu.edu.cn/showproblem.php?pid=3452

2、题目大意:

给出一棵无向树,每条边都有权值,已知根节点是r,现在要删除部分边,使得所有的叶子结点都不与根连通,求删掉的这些边的最小权值和是多少?

首先我们要从根节点开始遍历,从子节点更新到父节点,用dp[i]表示以i结点为根的子树保证子节点不连通最小代价和,那么dp[r]即所求

dp[i]+=min(w[i],dp[j]);dp[j]是i的子节点



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 ui vi wi (where ui, vi ∈ {1,……, n} and 0 <= wi <= 1000) indicating that vertex ui is connected to vertex vi by an undirected edge with weight wi. 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 151 2 12 3 22 5 35 6 74 6 56 7 45 15 615 10 1110 13 513 14 412 13 39 10 88 9 29 11 30 0

Sample Output

16

#include<iostream>#include<cstdio>#include<cstring>#include<algorithm>#include<vector>#include<queue>#pragma comment(linker, "/STACK:10240000,10240000")//递归太深,导致爆栈,所以使用扩栈语句using namespace std;int dp[1111],num[1111][1111],vis[1111];int m,n;vector<int>vv[1111];const int inf = 0x3f3f3f3f;void dfs(int r){int i,j,len=vv[r].size();vis[r]=1;if(len==1&&r!=m) dp[r]=inf;for(i=0;i<len;i++) {int son=vv[r][i];if(vis[son]) continue;dfs(son);dp[r]+=min(dp[son],num[r][son]);}}int main(){int i,j,t,u,v;while(scanf("%d%d",&n,&m)!=EOF) {if(n==0&&m==0) break;for(i=1;i<=n;i++) {vis[i]=0;dp[i]=0;vv[i].clear();}for(i=1;i<n;i++) {scanf("%d%d%d",&u,&v,&t);num[u][v]=num[v][u]=t;vv[u].push_back(v);vv[v].push_back(u);}dfs(m);printf("%d\n",dp[m]);}return 0;} 





0 0