树直径,节点最远距离 hdu 2196

题意:求每个节点的最远距离

分析:dfs1 求出直径的两个端点, dfs2 遍历每个点到端点的距离( 因为最远距离在该点到直径中的一个端点 )

#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=2;i<=N;++i)
        {
            LL a,b,c;
            scanf("%lld%lld",&a,&b);
            G[i].push_back(Edge(a,b));
            G[a].push_back(Edge(i,b));
        }
        dfs1(1,-1);
        memset(dis,0,sizeof(dis));
        dfs2(V1,-1,0);
        dfs2(V2,-1,1);
        for(LL u=1;u<=N;++u)
        {
            if(u==V1||u==V2)
               cout << L << endl;
            else cout << max(dis[0][u],dis[1][u]) << endl;
        }
    }
    return 0;
}


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值