【JZOJ 5455】拆网线 【树形DP】

#题目大意:

题目链接:https://jzoj.net/senior/#main/show/5455
题目图片:
http://www.z4a.net/images/2018/09/15/Screenshot.png
http://www.z4a.net/images/2018/09/15/Screenshot-1.png
给出一棵树,要选择其中 m m m个结点,输出在保证选择的节点都有初度的情况下最少的边数。


思路:

由于任意两个选择的点相连就可以满足要求,所以可以先找出这棵树上的最大点对。
f [ i ] [ 0 ] f[i][0] f[i][0]表示不选择第 i i i个点,以 i i i为根的子树的点对数量。
f [ i ] [ 1 ] f[i][1] f[i][1]表示选择第 i i i个点,以 i i i为根的子树的点对数量。
那么如果不选择第 i i i个点,那么它的所有子节点都可以选,就有
f [ x ] [ 0 ] = ∑ i = 1 s o n [ x ] f [ y ] [ 1 ] f[x][0]=\sum^{son[x]}_{i=1}f[y][1] f[x][0]=i=1son[x]f[y][1]
那么如果选择第 i i i个点,那么就必须有一个子节点空出来,这样才能形成点对,那么就有
f [ x ] [ 1 ] = m a x ( f [ x ] [ 1 ] , f [ x ] [ 0 ] − f [ y ] [ 1 ] + f [ y ] [ 0 ] + 1 ) f[x][1]=max(f[x][1],f[x][0]-f[y][1]+f[y][0]+1) f[x][1]=max(f[x][1],f[x][0]f[y][1]+f[y][0]+1)
那么最大点对就是 a n s = m a x ( f [ 1 ] [ 0 ] , f [ 1 ] [ 1 ] ) ans=max(f[1][0],f[1][1]) ans=max(f[1][0],f[1][1])
那么如果 m ≤ a n s × 2 m\leq ans\times 2 mans×2,那么显而易见答案是 ( k + 1 ) / 2 (k+1)/2 (k+1)/2
但是如果 m > a n s m>ans m>ans,那么那 a n s ans ans个点对我们能选就选,总共可以选 a n s × 2 ans\times 2 ans×2,那么就还有 m − a n s × 2 m-ans\times 2 mans×2个没有选,由于没有可选的点对了,那么剩余的点就只能一个点用一条边连着,所以答案就是 a n s + ( m − a n s × 2 ) ans+(m-ans\times 2) ans+(mans×2)


代码:

#include <cstdio>
#include <cstring>
#include <algorithm>
#define N 100100
using namespace std;

int t,n,m,x,tot,f[N][2],head[N];

struct edge
{
	int to,next;
}e[N];

int read()  //不开快读会T
{
    int ans=0; 
	char c=getchar();
    while (c<48||c>57) c=getchar();
    while (c>47&&c<58) 
    {
    	ans=(ans<<3)+(ans<<1)+c-48;
		c=getchar();
    }
    return ans;
}

void add(int from,int to)
{
	tot++;
	e[tot].to=to;
	e[tot].next=head[from];
	head[from]=tot;
}

void dp(int u)
{
	for (int i=head[u];~i;i=e[i].next)
	{
		int v=e[i].to;
		dp(v);
		f[u][0]+=f[v][1];
	}
	for (int i=head[u];~i;i=e[i].next)
	{
		int v=e[i].to;
		f[u][1]=max(f[u][1],f[u][0]-f[v][1]+f[v][0]+1);
	}
}

int main()
{
	t=read();
	while (t--)
	{
		tot=0;
		memset(head,-1,sizeof(head));
		memset(f,0,sizeof(f));
		n=read();
		m=read();
		for (int i=2;i<=n;i++)
		{
			x=read();
			add(x,i);
		}
		dp(1);
		int ans=max(f[1][0],f[1][1]);
		if (ans*2>=m) printf("%d\n",(m+1)/2);
		 else printf("%d\n",ans+(m-ans*2));
	}
	return 0;
}
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值