[BZOJ2404]最长链

题目描述

给定一棵有n个节点的树,求每个节点到其他节点的最大距离


输入
输入第一行是一个自然数n(n≤10000), 接下来 (n−1) 行描述: 

第i行包含两个自然数 , 表示编号为i的节点连接到的节点编号和这条网线的长度..距离总长不会超过10^9. 每行中的两个数字用空格隔开.


输出

输出包含n行. 第i行表示对于离编号为i的节点最远的节点与该节点的距离Si(1≤i≤n).


样例输入
3
1 1

1 2


样例输出
2
3

3



题解:
做三次DFS
第一次:任选一点为根,找出离它最远的点s;
第二次:以s为根,找出离它最远的点e,同时算出所有点距s的距离;
第三次:以e为根,同时算出所有点距e的距离,与距s的距离取较大值,得出答案。
证明:点s到点e的距离是这棵树的直径,可以保证树中任意两点间的距离dis(i, j)≤dis(s, e)。所以对一个点,它的 最远的节点不是s就是e。

也可以用树型DP做,给一位大佬的链接:http://blog.csdn.net/its_elaine/article/details/69095357


#include<iostream> 
#include<cstring> 
#include<cstdio> 
#include<cstdlib> 
#include<cmath> 
#include<algorithm> 
using namespace std; 
const int N=1e4+10; 
int dis[N], s, e, w; 
int n, fir[N], ecnt; 
struct node{ int e, w, next; }edge[N<<1]; 
  
void Link( int s, int e, int w ) { 
    edge[++ecnt].e=e; edge[ecnt].w=w; 
    edge[ecnt].next=fir[s]; fir[s]=ecnt; 
    edge[++ecnt].e=s; edge[ecnt].w=w; 
    edge[ecnt].next=fir[e]; fir[e]=ecnt; 
} 
  
void DFS( int r, int fa, int L, int &e ) { 
    dis[r]=max( dis[r], L ); 
    if( ecnt<L ) ecnt=L, e=r; 
    for( int i=fir[r]; i; i=edge[i].next ) 
        if( edge[i].e!=fa ) 
            DFS( edge[i].e, r, L+edge[i].w, e ); 
} 
  
int main() { 
    scanf( "%d", &n ); 
    for( int i=2; i<=n; i++ ) 
        scanf( "%d%d", &e, &w ), 
        Link( i, e, w ); 
    ecnt=0;DFS( 1, -1, 0, s ); 
    ecnt=0;DFS( s, -1, 0, e ); 
    DFS( e, -1, 0, s ); 
    for( int i=1; i<=n; i++ ) printf( "%d\n", dis[i] ); 
    return 0; 
} 


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值