版权声明:若希望转载,在评论里直接说明即可,谢谢! https://blog.csdn.net/SSL_ZYC/article/details/82715156
题目大意:
题目链接: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
给出一棵树,要选择其中
个结点,输出在保证选择的节点都有初度的情况下最少的边数。
思路:
由于任意两个选择的点相连就可以满足要求,所以可以先找出这棵树上的最大点对。
设
表示不选择第
个点,以
为根的子树的点对数量。
表示选择第
个点,以
为根的子树的点对数量。
那么如果不选择第
个点,那么它的所有子节点都可以选,就有
那么如果选择第 个点,那么就必须有一个子节点空出来,这样才能形成点对,那么就有
那么最大点对就是
那么如果 ,那么显而易见答案是 。
但是如果 ,那么那 个点对我们能选就选,总共可以选 ,那么就还有 个没有选,由于没有可选的点对了,那么剩余的点就只能一个点用一条边连着,所以答案就是 。
代码:
#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;
}