[BZOJ2404]最长链
来源:互联网 发布:淘宝宝贝规格怎么设置 编辑:程序博客网 时间:2024/06/17 22:00
题目描述给定一棵有n个节点的树,求每个节点到其他节点的最大距离
输入输入第一行是一个自然数n(n≤10000), 接下来 (n−1) 行描述:第i行包含两个自然数 , 表示编号为i的节点连接到的节点编号和这条网线的长度..距离总长不会超过10^9. 每行中的两个数字用空格隔开.
输出输出包含n行. 第i行表示对于离编号为i的节点最远的节点与该节点的距离Si(1≤i≤n).
样例输入31 11 2
样例输出233
题解:做三次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
- [BZOJ2404]最长链
- #bzoj2404#最长链(树的直径/树形DP)
- 关于最长链
- problem14 最长链
- 最长词链
- 【最长链】wikioi1814
- Codevs P1814 最长链
- P3250 最长链
- 【u219】最长链
- Codevs 1814 最长链
- 最长链(递归)
- Codevs 1814 最长链
- 树的最长链
- SSL P2034 最长链
- codevs 1814 最长链
- 最长
- 找出二维数组中的最长路径(最长链表)
- 最长不下降子序列—递归输出最长链
- 朴素贝叶斯(MLE&MAP)
- Oracle用户密码过期处理方法
- 跨域CORS
- 如何利用Vuforia6.2.10,在Unity2017中来实现AR中的虚拟按钮功能
- ajax技术以及json格式转换
- [BZOJ2404]最长链
- 获取中文字符串的第一个大写字母
- POJ 3648Wedding (2-SAT 输出路径)
- java 字符串,字符数组,list间的转化
- jdbc的连接
- Jenkins 使用QR-Code生成二维码 ImportError: No module named PIL
- Servlet、listener、filter、InitParam注解
- Spring应用总结
- 最短路模板