2017 湘潭邀请赛 H Highway(树的直径)

87 篇文章 0 订阅



题目大意:

    在一棵树上,任意两点以距离为边,求最大生成树。


解题思路:

    首先,树的直径一定在所求生成树中。由Prim算法构造生成树的过程可知,一定优先选择距离当前集合最远的点。树的直径有一个性质,任何一个点的最远点一定是直径两端点中的一个。所以我们就可以知道每个点加入集合时,答案增加一定是这个点到直径两个端点中较远的一个。

    树的直径可以用树形DP求得,然后对每个端点分别dfs一边得到到每个点的距离。最后把除了端点以外的点扫一遍,取距离最大值加起来即可。


AC代码:

#include <iostream>
#include <algorithm>
#include <cstdio>
#include <cstring>
#include <vector>
#include <queue>
#include <cmath>
using namespace std;
#define LL long long
#define INF 0x3f3f3f3f
#define fi first
#define se second
#define mem(a,b) memset((a),(b),sizeof(a))

const LL MAXV=100000+3;

struct Edge//边
{
    LL to,cost;
    Edge(LL t,LL c):to(t),cost(c){}
};

LL N,L,V1,V2,ans;
vector<Edge> G[MAXV];//邻接表存树
LL dp[MAXV],deep[MAXV],dis[2][MAXV];

void init()//初始化
{
    for(LL i=1;i<=N;++i)
    {
        G[i].clear();
        dp[i]=0;
        deep[i]=i;
    }
    L=0;
    ans=0;
}

void dfs1(LL u,LL fa)//树形dp求直径
{
    LL the_max=0,the_second=0,v1=u,v2=u;
    for(LL i=0;i<G[u].size();++i)
    {
        LL v=G[u][i].to;
        if(v==fa)
            continue;
        dfs1(v,u);
        LL now_dis=dp[v]+G[u][i].cost;
        if(now_dis>the_max)
        {
            the_second=the_max;
            v2=v1;
            the_max=now_dis;
            v1=deep[v];
        }
        else if(now_dis>the_second)
        {
            the_second=now_dis;
            v2=deep[v];
        }
    }
    dp[u]=the_max;
    deep[u]=v1;
    if(the_max+the_second>L)
    {
        L=the_max+the_second;
        V1=v1;
        V2=v2;
    }
}

void dfs2(LL u,LL fa,LL id)//求某一个点到其他距离的点
{
    for(LL i=0;i<G[u].size();++i)
    {
        LL v=G[u][i].to;
        if(v==fa)
            continue;
        dis[id][v]=dis[id][u]+G[u][i].cost;
        dfs2(v,u,id);
    }
}

int main()
{
    while(~scanf("%lld",&N))
    {
        init();
        for(LL i=0;i<N-1;++i)
        {
            LL a,b,c;
            scanf("%lld%lld%lld",&a,&b,&c);
            G[a].push_back(Edge(b,c));
            G[b].push_back(Edge(a,c));
        }
        dfs1(1,-1);
        ans+=L;
        dis[0][V1]=0;
        dfs2(V1,-1,0);
        dis[1][V2]=0;
        dfs2(V2,-1,1);
        for(LL u=1;u<=N;++u)
        {
            if(u==V1||u==V2)
                continue;
            ans+=max(dis[0][u],dis[1][u]);
        }
        printf("%lld\n",ans);
    }
    
    return 0;
}

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值