[BZOJ2404]最长链

来源:互联网 发布:淘宝宝贝规格怎么设置 编辑:程序博客网 时间:2024/06/17 22:00
题目描述

给定一棵有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; }