近期在刷 PAT 题库的时候遇到一个求树的最长根的问题, 觉得证明挺有意思的, 于是抽空记录下来.
1021 Deepest Root(25 分)
A graph which is connected and acyclic can be considered a tree. The hight of the tree depends on the selected root. Now you are supposed to find the root that results in a highest tree. Such a root is called the deepest root.
Input Specification:
Each input file contains one test case. For each case, the first line contains a positive integer N (≤10^4) which is the number of nodes, and hence the nodes are numbered from 1 to N. Then N−1 lines follow, each describes an edge by given the two adjacent nodes’ numbers.
Output Specification:
For each test case, print each of the deepest roots in a line. If such a root is not unique, print them in increasing order of their numbers. In case that the given graph is not a tree, print Error: K components where K is the number of connected components in the graph.
Sample Input 1:
1 | 5 |
Sample Output 1:
1 | 3 |
Sample Input 2:
1 | 5 |
Sample Output 2:
1 | Error: 2 components |
题目分析
这道题首先要求我们判断输入的图能否构成一棵树. 如果能构成一棵树就按节点序号顺序输出这棵树的最长根节点, 最长根节点是能让一棵树的深度达到最大值的节点. 如果不能构成一棵树就输出错误, 并报告图的联通部分个数.
在确定能构成了一棵树后, 使用两次 dfs 或 bfs 搜索算法就能找到所有的最长根节点. 下面证明这个结论:
假设树的最大深度为 maxD. 首先以任意一点作为树的根节点, 假设第一次搜索出的叶子节点为 L = {L1, L2, …, Ln}. 对应的节点深度为 {A1, A2, …, An}. 节点深度的最大值为 maxA, 对应的节点集合假设为 {Lmax}. 从 L 中任选两个叶子节点的组合, 所有组合之间的距离最大值就是该树所能达到的最大深度 maxD.
若找到了 i 和 j , 使得 maxD = Li 和 Lj 对应的深度, 不妨设 Ai >= Aj.
若Li和Lj不在同一支上, 则Li和Lj对应的深度 = Ai + Aj
另一方面, Ai + Aj <= maxA + Aj <= maxD.
所以, Ai + Aj = maxA + Aj = maxD, maxA = Ai, Ai 属于 {Lmax}. 根据定义, {Lmax} 集合中的元素为最长根节点.
第二次搜索从 {Lmax} 中任选一个元素, 即选择一个已经找到的最长根节点 D1. 根据定义, 以该点为根形成的树的最大深度是 maxD. 对应最大深度的节点假设为 Di, 那么反过来以 Di 为根产生的树的最大深度也是 maxD. 所以 Di 也是最长根节点.接下来还要证明已经找出了所有的最长根节点.
实例代码
1 | #include<stdio.h> |
Comments
shortname
for Disqus. Please set it in_config.yml
.