bzoj2525 [Poi2011]Dynamite 二分答案+贪心

Description


Byteotian Cave的结构是一棵N个节点的树,其中某些点上面已经安置了炸药,现在需要点燃M个点上的引线引爆所有的炸药。
某个点上的引线被点燃后的1单位时间内,在树上和它相邻的点的引线会被点燃。如果一个有炸药的点的引信被点燃,那么这个点上的炸药会爆炸。
求引爆所有炸药的最短时间。

1<=m<=n<=300000

Solution


可以发现实际上要求的就是选择点到所有炸药点的最大距离最小,这个可以二分答案,然后我就不会做了
一个说法是:如果选择的代价相等那么就是贪心,如果选择代价不等那么就是dp
记fir[x]表示节点x为根的子树中未选择的点到x的最大距离
记sec[x]表示节点x为根的子树中选择的点到x的最小距离
若fir[x]==mid表示节点x一定得选
若fir[x]+sec[x]<=mid表示节点x为根的子树中所有炸药都被距离不大于mid的选择点覆盖了

就是这样

Code


#include <stdio.h>
#include <string.h>
#include <algorithm>
#define rep(i,st,ed) for (int i=st;i<=ed;++i)

const int INF=0x3f3f3f3f;
const int N=800005;

struct edge {int y,next;} e[N];

int ls[N],edCnt,tot;
int a[N],fir[N],sec[N];
int n,m;

void add_edge(int x,int y) {
    e[++edCnt]=(edge) {y,ls[x]}; ls[x]=edCnt;
    e[++edCnt]=(edge) {x,ls[y]}; ls[y]=edCnt;
}

void dfs(int now,int fa,int mid) {
    fir[now]=-INF; sec[now]=INF;
    for (int i=ls[now];i;i=e[i].next) {
        if (e[i].y==fa) continue;
        dfs(e[i].y,now,mid);
        fir[now]=std:: max(fir[now],fir[e[i].y]+1);
        sec[now]=std:: min(sec[now],sec[e[i].y]+1);
    }
    if (a[now]&&sec[now]>mid) fir[now]=std:: max(0,fir[now]);
    if (fir[now]+sec[now]<=mid) fir[now]=-INF;
    if (fir[now]==mid) fir[now]=-INF,sec[now]=0,tot++;
}

bool check(int mid) {
    tot=0;
    dfs(1,0,mid);
    if (fir[1]>=0) tot++;
    return tot<=m;
}

int main(void) {
    scanf("%d%d",&n,&m);
    rep(i,1,n) scanf("%d",&a[i]);
    rep(i,2,n) {
        int x,y; scanf("%d%d",&x,&y);
        add_edge(x,y);
    }
    int ans=0;
    for (int l=0,r=n;l<=r;) {
        int mid=(l+r)>>1;
        if (check(mid)) ans=mid,r=mid-1;
        else l=mid+1;
    }
    printf("%d\n", ans);
    return 0;
}

猜你喜欢

转载自blog.csdn.net/jpwang8/article/details/80472656
今日推荐