# 1021 Deepest Root (25分)

##### 1021 Deepest Root (25分)

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 (≤ 1 0 4 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 components


##### 题解：
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
vector<int> v;
int visited{ 0 };
int dp{ 0 };
int max_depth = -1;
void dfs(int j, int depth) {
visited[j] = 1;
max_depth = depth > max_depth ? depth : max_depth;
for (int i = 0; i < v[j].size(); i++) {
if (!visited[v[j][i]])
dfs(v[j][i], depth + 1);
}
}
int main() {
int n,c1,c2,depth=0,k=0;
scanf("%d", &n);
for (int i = 0; i < n - 1; i++) {
scanf("%d%d", &c1, &c2);
v[c1].push_back(c2);
v[c2].push_back(c1);
}
for (int i = 1; i <= n; i++) {
if (!visited[i]) {
dfs(i, depth);
k++;
}
}
if (k > 1)
printf("Error: %d components\n",k);
else {
for (int i = 1; i <= n; i++) {
max_depth = -1; depth = 0;
fill(visited, visited + 10001, 0);
dfs(i, depth);
dp[i] = max_depth;
}
int m = *max_element(dp + 1, dp + n + 1);
for (int i = 1; i <= n; i++)
if (dp[i] == m)
printf("%d\n", i);
}
return 0;
}

10-03 1039
09-21 313 01-01 332
06-21 74
12-06 60
10-21 329
12-15 466
02-19 133
08-28 200