pat

题目

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 (≤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:

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 componets

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58

#include <cstdio>
#include <vector>
#include <set>
using namespace std;
typedef vector<int> vi;
vector<vi> AdjList;
vi vst, tmp;
int N, a, b, c, cnt, max_height;
set<int> s;
void (int u, int height){
if(height > max_height){
tmp.clear();
tmp.push_back(u);
max_height = height;
}else if(height == max_height)
tmp.push_back(u);
vst[u] = 1;
for(int i = 0;i < (int)AdjList[u].size();i++){
int v = AdjList[u][i];
if(vst[v] == -1){
dfs(v, height + 1);
vst[v] = 1;
}else continue;
}
}
int main(){
scanf("%d", &N);
AdjList.assign(N+1, vi());
vst.assign(N+1, -1);
for(int i = 0;i < N-1;i++){
scanf("%d %d", &a, &b);
AdjList[a].push_back(b);
AdjList[b].push_back(a);
}
for(int i = 1;i <= N;i++){
if(vst[i] == -1)
dfs(i, 1), cnt++;
if(i == 1){
if(tmp.size() != 0) c = tmp[0];
for(auto iter = tmp.begin(); iter != tmp.end(); iter++)
s.insert(iter);
}
}
if(cnt != 1)
printf("Error: %d componentsn", cnt);
else {
tmp.clear();
max_height = 0;
fill(vst.begin(), vst.end(), -1);
dfs(c, 1);
for(auto iter = tmp.begin(); iter != tmp.end(); iter++)
s.insert(
iter);

for(auto iter = s.begin(); iter != s.end(); iter++)
printf("%dn", *iter);
}
return 0;
}