题目大意:
题目链接:https://www.luogu.org/problemnew/show/P3554
给一颗树,1号节点已经被染黑,其余是白的,两个人轮流操作,一开始B在1号节点,A选择k个点染黑,然后B走一步,如果B能走到A没染的节点则B胜,否则当A染完全部的点时,A胜。求能让A获胜的最小的k。
思路:
这个
k
k
k比较恶心,可以二分答案使题目变成一个判定性问题。
若
m
i
d
mid
mid为我们二分的答案,设
f
[
x
]
f[x]
f[x]表示以
x
x
x为根的子树还需要染色的数目。
由于B肯定只会往叶子节点走,而且染色的数目必然大于0,所以有方程
f
[
x
]
=
m
a
x
(
0
,
∑
f
[
y
]
+
o
u
t
[
x
]
−
m
i
d
)
(
y
∈
s
o
n
[
x
]
)
f[x]=max(0,\sum f[y]+out[x]-mid)(y\in son[x])
f[x]=max(0,∑f[y]+out[x]−mid)(y∈son[x])
其中
o
u
t
[
x
]
out[x]
out[x]表示
x
x
x的子节点个数。
最后如果
f
[
x
]
>
0
f[x]>0
f[x]>0,说明在每次染
m
i
d
mid
mid个的情况下依然不可以把B围住,若
f
[
x
]
=
0
f[x]=0
f[x]=0,则
m
i
d
mid
mid是一个合法的答案。
时间复杂度
O
(
n
log
n
)
O(n\log n)
O(nlogn)
代码:
#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\n",r+1);
return 0;
}