【洛谷P3554】LUK-Triumphal arch【树形dp】【二分】

题目大意:

题目链接:https://www.luogu.org/problemnew/show/P3554
给一颗树,1号节点已经被染黑,其余是白的,两个人轮流操作,一开始B在1号节点,A选择k个点染黑,然后B走一步,如果B能走到A没染的节点则B胜,否则当A染完全部的点时,A胜。求能让A获胜的最小的k。


思路:

这个kk比较恶心,可以二分答案使题目变成一个判定性问题。
midmid为我们二分的答案,设f[x]f[x]表示以xx为根的子树还需要染色的数目。
由于B肯定只会往叶子节点走,而且染色的数目必然大于0,所以有方程
f[x]=max(0,f[y]+out[x]mid)(yson[x])f[x]=max(0,sum f[y]+out[x]-mid)(yin son[x])
其中out[x]out[x]表示xx的子节点个数。
最后如果f[x]>0f[x]>0,说明在每次染midmid个的情况下依然不可以把B围住,若f[x]=0f[x]=0,则midmid是一个合法的答案。
时间复杂度O(nlogn)O(nlog n)


代码:

#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;

const int N=300010;
int n,x,y,tot,l,r,mid,f[N],head[N];

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

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

void dp(int x,int fa)
{
    int sum=0;
    for (int i=head[x];~i;i=e[i].next)
    {
        int y=e[i].to;
        if (y!=fa)
        {
            dp(y,x);
            sum+=f[y]+1;
        }
    }
    f[x]=max(0,sum-mid);
}

int main()
{
    memset(head,-1,sizeof(head));
    scanf("%d",&n);
    for (int i=1;i<n;i++)
    {
        scanf("%d%d",&x,&y);
        add(x,y); add(y,x);
    }
    l=0; r=n-1;
    while (l<=r)
    {
        mid=(l+r)/2;
        dp(1,0);
        if (!f[1]) r=mid-1;
            else l=mid+1;
    }
    printf("%d
",r+1);
    return 0;
}
原文地址:https://www.cnblogs.com/hello-tomorrow/p/11998110.html