poj 1947 Rebuilding Roads(树型DP)
来源:互联网 发布:苏联解体中国反应 知乎 编辑:程序博客网 时间:2024/06/05 02:12
题意:给定一棵树,问最少删除多少条边,可以出现一个含有p个节点的子树。
思路:可以删除的的边当作背包,问最少需要多小的包可以删除特定数量的节点。题目转变成了树型背包问题。需要注意有可能1不在最后的子树里面。我没想到什么好的解决方法,干脆以所有节点作为根都计算了一遍。数据范围比较小,所以也过了。
我AC之后看到了别人更加优雅的解法:点击打开链接。不过现在太困了,等睡醒了再看。
#include<stdio.h>#include<string.h>const int N=155;const int inf=0x3f3f3f3f;int dp[N][N],head[N],vis[N];int cnt;int n,m;struct node{ int son; int next;}Edge[N*2];int Min(int x,int y){ if(x<y) return x; else return y;}void AddEdge(int x,int y){ Edge[cnt].son=y;Edge[cnt].next=head[x];head[x]=cnt++; Edge[cnt].son=x;Edge[cnt].next=head[y];head[y]=cnt++; return ;}int dfs(int father){ vis[father]=1; int count=1; int last_son=0; for(int i=head[father];i!=-1;i=Edge[i].next) { int son=Edge[i].son; if(vis[son]) continue; int cnt=dfs(son); count+=cnt; dp[father][cnt]=1; for(int j=1;j<=cnt;j++) { for(int k=m;k>=j;k--) { if(dp[last_son][k-j]!=inf) { if(j!=cnt) dp[father][k]=Min(dp[father][k],dp[last_son][k-j]+dp[son][j]); else dp[father][k]=Min(dp[father][k],dp[last_son][k-j]+1); } } } for(int j=1;j<=m;j++) { dp[son][j]=dp[father][j]; } last_son=son; } if(count==1) { dp[father][1]=1; } return count;}int main(){ while(scanf("%d%d",&n,&m)!=EOF) { m=n-m; cnt=1; memset(head,-1,sizeof(head)); for(int i=1;i<n;i++) { int x,y; scanf("%d%d",&x,&y); AddEdge(x,y); } int ans=inf; for(int i=1;i<=n;i++) { memset(dp,0x3f,sizeof(dp)); for(int j=0;j<=m;j++) { dp[j][0]=0; } memset(vis,0,sizeof(vis)); dfs(i); for(int j=0;j<=m;j++) { ans=Min(ans,dp[j][m]); } } printf("%d\n",ans); } return 0;}
0 0
- poj 1947 Rebuilding Roads(树型DP)
- 【POJ 1947】Rebuilding Roads(树型DP)
- (POJ 1947)Rebuilding Roads <树型DP>
- poj 1947 Rebuilding Roads 树型dp
- poj 1947 Rebuilding Roads(树形dp)
- POJ 1947 Rebuilding Roads(树形DP)
- POJ 1947 Rebuilding Roads(树形DP)
- POJ 1947 Rebuilding Roads (树形dp)
- 树形dp(poj 1947 Rebuilding Roads )
- POJ 1947 - Rebuilding Roads 树型DP(泛化背包转移)..
- POJ 1947/hrbust 2098 Rebuilding Roads【树型dp】
- POJ 1947 Rebuilding Roads(树形DP + 01背包)
- POJ 1947 Rebuilding Roads(动态规划-树形DP)
- POJ题目1947 Rebuilding Roads(树形dp)
- POJ 1947 Rebuilding Roads (树形dp + 01背包)
- POJ--1947[Rebuilding Roads] 树形DP
- POJ 1947 Rebuilding Roads 树形DP
- POJ 1947 Rebuilding Roads 树形dp
- hibernate总结
- 基于Redis实现分布式消息队列(2)
- leetcode - Maximum Depth of Binary Tree C#
- 哈夫曼编码
- win7+ubuntu双系统安装
- poj 1947 Rebuilding Roads(树型DP)
- 一、前言
- 黑马程序员IOS基础---之C to OC
- 二分查找(折半查找),Java实现
- eclipse优化方法
- vim 中:wq和:wq的不同之处
- JAVA菜鸟入门(14) Anonymous Class 和 final variable
- 发生根本h放大按本规定
- Leetcode 208: Implement Trie (Prefix Tree)