题意:给定一棵树,问最少删除多少条边,可以出现一个含有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;
}