COCI2014/2015 Contest#1 F KAMP(树形DP+转移答案)

版权声明:我这种蒟蒻的文章,真正的大佬一般看不上的_(:з」∠)_ https://blog.csdn.net/Paulliant/article/details/82894822

题意

给定一棵 n n 个节点的树表示一个村庄,现在有 m m 个人需要救援。救援人员任选一个起点,按任意顺序救出 m m 个点上的人,最后停留在最后一个救的人的位置上,求最短的总路程。
1 m n 5 × 1 0 5 1 \leq m \leq n \leq 5\times 10^5

思路

先分析答案,假设它从某个节点出发,由于救人一来一回所以需要遍历的边要遍历两次,但最后又可以停留在任意救援地点,所以最终的答案就是需要遍历的边权和的两倍,减去最远能到的救援地点距离,设前者为 a a ,后者为 b b
不难发现,所有点能到最远的救援地点距离可以用求最远距离一样的方法,三遍 dfs \text{dfs} 解决,只需在判更新直径是加一句是否为救援点的判断即可,拉出的直径两头都是救援点,不是最长的直径,可以称它为“伪直径”(求直径的方法可以用在求到所有合法点的最远距离上)。
然后任选一个作为根,可以一遍 dfs \text{dfs} 搞出以这个根为出发点的 a a 值。在转移答案,如果下面没有救援点就加上两倍边权,上面没有救援点就减去两倍边权,否则不变。
分析答案构成,再套用适当的方法解决,是解决这类问题的可行思路。

代码

#include<bits/stdc++.h>
#define FOR(i,x,y) for(int i=(x),i##END=(y);i<=i##END;++i)
#define DOR(i,x,y) for(int i=(x),i##END=(y);i>=i##END;--i)
typedef long long LL;
using namespace std;
const int N=5e5+3;
template<const int maxn,const int maxm>struct Linked_list
{
    int head[maxn],to[maxm],cost[maxm],nxt[maxm],tot;
    void clear(){memset(head,-1,sizeof(head));tot=0;}
    void add(int u,int v,int w){to[++tot]=v,cost[tot]=w,nxt[tot]=head[u],head[u]=tot;}
    #define EOR(i,G,u) for(int i=G.head[u];~i;i=G.nxt[i])
};
Linked_list<N,N<<1>G;
int n,m,Dx;
int cnt[N],Scnt[N];
LL dp[N],dis[N],Dis,sum;
 
void dfs(int u,int f)
{
    dp[u]=0,Scnt[u]=cnt[u];
    EOR(i,G,u)
    {
        int v=G.to[i],w=G.cost[i];
        if(v==f)continue;
        dfs(v,u);
        Scnt[u]+=Scnt[v];
        if(Scnt[v])sum+=2*w;
    }
}
 
 
void Dsolve(int u,int f,LL D)
{
    dis[u]=max(dis[u],D);
    if(D>Dis&&cnt[u])Dis=D,Dx=u;
    EOR(i,G,u)
    {
        int v=G.to[i],w=G.cost[i];
        if(v==f)continue;
        Dsolve(v,u,D+w);
    }
}
 
void redfs(int u,int f,LL Ds)
{
    dp[u]=Ds-dis[u];
    EOR(i,G,u)
    {
        int v=G.to[i],w=G.cost[i];
        if(v==f)continue;
        if(Scnt[v]==0)redfs(v,u,Ds+2*w);
        else if(m-Scnt[v]==0)redfs(v,u,Ds-2*w);
        else redfs(v,u,Ds);
    }
}
   
int main()
{
    G.clear();
    scanf("%d%d",&n,&m);
    FOR(i,1,n-1)
    {
        int u,v,w;
        scanf("%d%d%d",&u,&v,&w);
        G.add(u,v,w);
        G.add(v,u,w);
    }
    FOR(i,1,m)
    {
        int t;
        scanf("%d",&t);
        cnt[t]++;
    }
    dfs(1,0);
    memset(dis,0,sizeof(dis));
    Dis=-1;Dsolve(1,0,0);
    memset(dis,0,sizeof(dis));
    Dis=-1;Dsolve(Dx,0,0);
    Dis=-1;Dsolve(Dx,0,0);
    redfs(1,0,sum);
    FOR(i,1,n)printf("%lld\n",dp[i]);
    return 0;
}

猜你喜欢

转载自blog.csdn.net/Paulliant/article/details/82894822