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

版权声明:若希望转载,在评论里直接说明即可,谢谢! 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
给出一棵树,要选择其中 m 个结点,输出在保证选择的节点都有初度的情况下最少的边数。


思路:

由于任意两个选择的点相连就可以满足要求,所以可以先找出这棵树上的最大点对。
f [ i ] [ 0 ] 表示不选择第 i 个点,以 i 为根的子树的点对数量。
f [ i ] [ 1 ] 表示选择第 i 个点,以 i 为根的子树的点对数量。
那么如果不选择第 i 个点,那么它的所有子节点都可以选,就有

f [ x ] [ 0 ] = i = 1 s o n [ x ] f [ y ] [ 1 ]

那么如果选择第 i 个点,那么就必须有一个子节点空出来,这样才能形成点对,那么就有
f [ x ] [ 1 ] = m a x ( 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 ] )
那么如果 m a n s × 2 ,那么显而易见答案是 ( k + 1 ) / 2
但是如果 m > a n s ,那么那 a n s 个点对我们能选就选,总共可以选 a n s × 2 ,那么就还有 m a n s × 2 个没有选,由于没有可选的点对了,那么剩余的点就只能一个点用一条边连着,所以答案就是 a n s + ( m a n s × 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;
}

猜你喜欢

转载自blog.csdn.net/SSL_ZYC/article/details/82715156
今日推荐