求树的直径端点和距离

对树的直径的讲解

http://hihocoder.com/problemset/problem/1050

http://blog.csdn.net/fjsd155/article/details/6917291

#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 dfs(LL u,LL f)
{
    LL v1 = u,v2 = u;
    LL first = 0 , second = 0;
    for(int i = 0 ; i < G[u].size() ; ++i)
    {
        LL v = G[u][i].to;
        if( v== f )continue;
            dfs( v,u );
        LL now_dis=dp[v]+G[u][i].cost;
        if(now_dis>first)
        {
            second=first;
            v2=v1;
            first=now_dis;
            v1=deep[v];
        }
        else if(now_dis>second)
        {
            second=now_dis;
            v2=deep[v];
        }
    }
    dp[u] = first;
    deep[u] = v1;
    if(first+second>L){
        L=first+second;
        V1=v1;
        V2=v2;
    }
}



int main()
{
    while(~scanf("%lld",&N))
    {
        init();
        for(LL i=0;i<N-1;++i)
        {
            LL a,b,c;
            scanf("%lld%lld",&a,&b);
            G[a].push_back(Edge(b,1));
            G[b].push_back(Edge(a,1));
        }
        dfs(1,-1);
        cout << L << endl;
    }
    return 0;
}



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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值