【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
给出一棵树,要选择其中mm个结点,输出在保证选择的节点都有初度的情况下最少的边数。


思路:

由于任意两个选择的点相连就可以满足要求,所以可以先找出这棵树上的最大点对。
f[i][0]f[i][0]表示不选择第ii个点,以ii为根的子树的点对数量。
f[i][1]f[i][1]表示选择第ii个点,以ii为根的子树的点对数量。
那么如果不选择第ii个点,那么它的所有子节点都可以选,就有
f[x][0]=i=1son[x]f[y][1]f[x][0]=\sum^{son[x]}_{i=1}f[y][1]
那么如果选择第ii个点,那么就必须有一个子节点空出来,这样才能形成点对,那么就有
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)
那么最大点对就是ans=max(f[1][0],f[1][1])ans=max(f[1][0],f[1][1])
那么如果mans×2m\leq ans\times 2,那么显而易见答案是(k+1)/2(k+1)/2
但是如果m>ansm>ans,那么那ansans个点对我们能选就选,总共可以选ans×2ans\times 2,那么就还有mans×2m-ans\times 2个没有选,由于没有可选的点对了,那么剩余的点就只能一个点用一条边连着,所以答案就是ans+(mans×2)ans+(m-ans\times 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;
}
原文地址:https://www.cnblogs.com/hello-tomorrow/p/11998584.html