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.
Input Specification:
Each input file contains one test case. For each case, the first line contains a positive integer N (<=10000) 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:
5
1 2
1 3
1 4
2 5
Sample Output 1:
3
4
5
Sample Input 2:
5
1 3
1 4
2 5
3 4
Sample Output 2:
Error: 2 components
Solution
本题很关键的一个点是: 有 n 个顶点,但是只有 n-1 条边。由于构成一个连通图的无向图要求,n个顶点最少有n个边,因此本题可以看作为求 一个图的连通分量数目 以及 图的遍历。 对于图的遍历,可以采用 DFS 或者 BFS,求图的连通分量个数,可以采用并查集或者整合到图的遍历过程中
Code
1 |
|
- 本文标题:1021 Deepest Root (25分)
- 本文作者:codeflysafe
- 创建时间:2020-03-08 10:53:14
- 本文链接:https://codeflysafe.github.io/2020/03/08/2020-03-08-1021-Deepest-Root-(25分)/
- 版权声明:本博客所有文章除特别声明外,均采用 BY-NC-SA 许可协议。转载请注明出处!