DFS 遍历无向图;计算树的深度;计算连通分量个数。
A graph which is connected and acyclic can be considered a tree. The height 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.
Problem: PAT-A 1021 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 |
Analysis
判断无向图能否构成树结构,即是否为连通图、不成环。判断方法为计算无向图连通分量个数,如果大于 1 则为非连通图,输出错误提示。
使用两次 DFS 遍历无向图。第一次遍历选择任意结点作为树根,搜索到当前最深层的叶子结点,同时记录深度相同的叶子结点。第二次遍历,选择第一次遍历解集中的任意结点(最深层的叶子反过来也可以作为树根)作为根结点,获得第二次遍历的解集。两次遍历的解集取并集,使用 set 保存解集,去重并自动排序。
Code
1 |
|
Tsukkomi
没什么好吐槽的,继续学习。