PAT-Advanced-1021. Deepest Root

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:

Sample Output 1:

Sample Input 2:

Sample Output 2:


写了一个只能针对这道题的比较 low 的解法,没有通用性,(毕竟题目要求比较特殊)。首先,可以该无向图知道有 N 个节点和 N-1 条边,那么就可以通过并查集来判断共有多少个连通集。然后以每个节点为起点,进行深度优先搜索,记录最高的节点信息即可。




电子邮件地址不会被公开。 必填项已用*标注