树的直径算法(dfs)
1.什么是树的直径?
树的直径是一颗树中任意两点最长的距离
2.如何求树的直径?
(1).任意找一点x,并求得树上任意一点到x的距离存到数组dist中
(2).找到距离x最长的点y并以点y为起点找到树中距离y最远的点z,则z-y长度就是树的直径
3.证明y一定是某一直径的端点
acwing1207
#include <cstdio>
#include <cstring>
#include <iostream>
#include <algorithm>using namespace std;const int N = 100010;int n;
struct Edge
{int id, w;
};
vector<Edge> h[N];
int dist[N];void dfs(int u, int father, int distance)//
{dist[u] = distance;for (auto node : h[u])if (node.id != father)dfs(node.id, u, distance + node.w);
}int main()
{scanf("%d", &n);for (int i = 0; i < n - 1; i ++ ){int a, b, c;scanf("%d%d%d", &a, &b, &c);h[a].push_back({b, c});h[b].push_back({a, c});}dfs(1, -1, 0);int u = 1;for (int i = 1; i <= n; i ++ )if (dist[i] > dist[u])u = i;dfs(u, -1, 0);for (int i = 1; i <= n; i ++ )if (dist[i] > dist[u])u = i;int s = dist[u];printf("%lld\n", s * 10 + s * (s + 1ll) / 2);return 0;
}
树的直径算法(dfs)相关推荐
- 求树的直径算法以及证明
以下为两次dfs(bfs)的做法以及正确性证明. 算法步骤 (1)任取树上一点S,以S为源点BFS得S到各个顶点的d值: (2)取d值最大者之一为P,再以P为源点BFS得P到各个顶点的d值: (3)再 ...
- hdu 4607 Park Visit 求树的直径
题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=4607 Claire and her little friend, ykwd, are travelli ...
- 图论--树的直径--DFS+树形DP模板
#include <iostream> #include <cstring> using namespace std;//maxv:源点能到的最远点,maxdis:最远点对应的 ...
- 【POJ - 3310】Caterpillar(并查集判树+树的直径求树脊椎(bfs记录路径)+dfs判支链)
题干: An undirected graph is called a caterpillar if it is connected, has no cycles, and there is a pa ...
- 求树的直径+并查集(bfs,dfs都可以)hdu4514
题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=4514 这题主要是叫我们求出树的直径,在求树的直径之前要先判断一下有没有环 树的直径指的就是一棵树上面距 ...
- 【树上算法】树的直径
树的直径 一.什么是树的直径 直径往往和圆有关系.数学中,圆的直径是圆内最长的一条线段.那么在树中,树的直径就是树中最长的一段距离. 二.计算树的直径的思路 命题: ①在树上任取一个点x,找到距离x最 ...
- P1099 树的直径 DFS + 二分 / 尺取法
题意 传送门 P1099 树网的核 在任意一条直径上求出的最小偏心距都相等. 树上只有一条直径时显然成立.当树有多条直径,它们必定相交,且中点汇聚于同一处,那么中心附近树的各条直径的重叠部分是相同的, ...
- 算法提高——树上DP(树的直径)
文章目录 前言 一.什么是树的直径? 二.例题 三.树上DP 总结 前言 树的直径是图论里边非常高的考察点并且是入门树形dp的基础,竞赛的同学务必重视. 一.什么是树的直径? 树上最远两点(叶子结点) ...
- 【算法专题】树的直径
树的直径 定义:树中距离最远的两个点之间的距离被称为树的直径. 1 做法 做法一 (1)任取一点作为起点x,找到距离该点最远的一个点y: (2)再找到距离y最远的一点z,那么y.z之间的路径就是一条直 ...
最新文章
- C++ Primer 5th笔记(chap 14 重载运算和类型转换)标准库函数对象
- 今天收到 OCP 证书
- Oracle查询转换之连接谓词推入
- linux gcc 制作动态库
- 聊聊Lambda架构
- java中方法_java中的方法
- 洛谷P1156 垃圾陷阱【线性dp】
- Java开发工具Jcreator使用技巧总结
- win98装python_Windows 上的 Python安装
- Piranha介绍:过期代码自动删除的开源工具
- 开源网络准入系统(open source Network Access Control system)
- 360卫士锁定IE主页之更换主页
- python的一些报错解决
- 《沈剑架构师训练营》第5章 - 数据库架构
- excel表格横向纵向变换_什么是报表工具?和 EXCEL 有什么区别?
- 大数据与算法系列之算法性能分析
- python彩蛋_盘点Python的5大彩蛋
- 记来广州找实习1——还在找,还没找到。
- tableau:表计算
- 十五天学会Autodesk Inventor,看完这一系列就够了(七),工程图纸