某个点上的引线被点燃后的1单位时间内,在树上和它相邻的点的引线会被点燃。如果一个有炸药的点的引信被点燃,那么这个点上的炸药会爆炸。 求引爆所有炸药的最短时间。 1<=m<=n<=300000
分析
很显然这是要二分答案的,然后贪心一下就好了。
一开始想的贪心策略是每次找一个深度最大且未被覆盖的关键点,然后把这个点的第mid个祖先覆盖掉。 这个策略应该是没错的,但有个问题就是每选择一个点时,如果这个点已经被其他点覆盖了,我们要如何去标记那些在他范围内且没被覆盖的点。我没想到怎么处理,于是就放弃了。
正解是设fir[x]表示在x的子树内未被覆盖的关键点到x的最远距离,sec[x]表示x的子树中选择了的点到x的最近距离。然后如果sec[x]+fir[x]<=mid则证明x的子树可以自己解决。如果fir[x]==mid则要强制选x。 然后就没了。。
代码
using namespace std;
const
int N=
300005;
const
int inf=
0x3f3f3f3f;
int n,
m,cnt,
last[N],a[N],fir[N],sec[N],tot;
struct edge{
int to,
next;}e[N
*2];
int read()
{
int x=
0,f=
1;char ch=getchar();
while (ch<
'0'||ch>
'9'){
if(ch==
'-')f=-
1;ch=getchar();}
while (ch>=
'0'&&ch<=
'9'){
x=
x*10+ch-
'0';ch=getchar();}
return x*f;
}
void addedge(
int u,
int v)
{
e[++cnt].to=v;e[cnt].
next=
last[u];
last[u]=cnt;
e[++cnt].to=u;e[cnt].
next=
last[v];
last[v]=cnt;
}
void dfs(
int x,
int fa,
int mid)
{
fir[
x]=-inf;sec[
x]=inf;
for (
int i=
last[
x];i;i=e[i].
next)
{
if (e[i].to==fa)
continue;
dfs(e[i].to,
x,mid);
fir[
x]=max(fir[
x],fir[e[i].to]+
1);
sec[
x]=min(sec[
x],sec[e[i].to]+
1);
}
if (a[
x]&&sec[
x]>mid) fir[
x]=max(fir[
x],
0);
if (fir[
x]+sec[
x]<=mid) fir[
x]=-inf;
if (fir[
x]==mid) tot++,fir[
x]=-inf,sec[
x]=
0;
}
bool check(
int mid)
{
tot=
0;
dfs(
1,
0,mid);
if (fir[
1]>=
0) tot++;
if (tot<=
m)
return 1;
else return 0;
}
int main()
{
n=
read();
m=
read();
for (
int i=
1;i<=n;i++) a[i]=
read();
for (
int i=
1;i<n;i++)
{
int x=
read(),
y=
read();
addedge(
x,
y);
}
int l=
0,r=n;
while (l<=r)
{
int mid=(l+r)/
2;
if (check(mid)) r=mid-
1;
else l=mid+
1;
}
printf(
"%d",r+
1);
return 0;
}