# 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[10001];
int visited[10001]{ 0 };
int dp[10001]{ 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;
}

• 点赞
• 评论
• 分享
x

海报分享

扫一扫，分享海报

• 收藏
• 手机看

分享到微信朋友圈

x

扫一扫，手机阅读

• 打赏

打赏

gwang1_1

你的鼓励将是我创作的最大动力

C币 余额
2C币 4C币 6C币 10C币 20C币 50C币
• 一键三连

点赞Mark关注该博主, 随时了解TA的最新博文
10-03 1039

02-19 133