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 (≤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
中文题目
一个无环连通图可以被视作一个树。
树的高度取决于所选取的根节点。
现在,你要找到可以使得树的高度最大的根节点。
它被称为最深的根。
输入格式
第一行包含整数 N,表示节点数量。
节点编号为 1∼N。
接下来 N−1 行,每行包含两个整数,表示两个节点之间存在一条边。
输出格式
输出最深的根的节点编号。
如果最深的根不唯一,则按照从小到大的顺序,将它们依次输出,每个占一行。
如果给定的图不是树,输出 Error: K components,其中 K 是图中连通分量的数量。
数据范围
1≤N≤104
输入样例1:
5
1 2
1 3
1 4
2 5
输出样例1:
3
4
5
输入样例2:
5
1 3
1 4
2 5
3 4
输出样例2:
Error: 2 components
说明:首先我们先要判断是否只有一个连通分量(在这我们用并查集来判断是最快的也是最好写的),接下来我们看数据范围比较小那么我们判断根的深度直接用枚举然后dfs判断根的深度就好了
代码
#include<iostream>
#include<algorithm>
#include<vector>
using namespace std;
const int N = 10010;
int p[N];
int n;
vector<int>vv[N];
//并查集的查找函数+缩短路径
int find(int x) {
if (p[x] != x)p[x] = find(p[x]);
return p[x];
}
//判断深度
int dfs(int u, int father) {
int depth = 1;
for (int i = 0; i < vv[u].size(); i++) {
if (vv[u][i] != father) {
depth = max(depth, dfs(vv[u][i], u)+1);
}
}
return depth;
}
int main() {
cin >> n;
for (int i = 1; i <= n; i++) {
p[i] = i;
}
int t = n;
for (int i = 0; i < n-1; i++) {
int a, b;
cin >> a >> b;
//利用并查集来判断连通分量
if (find(a) != find(b)) {
t--;
p[find(a)] = find(b);
}
vv[a].push_back(b);
vv[b].push_back(a);
}
if (t > 1) {
cout << "Error: " << t << " components" << endl;
}
else {
vector<int>vv1;
int max_depth = -1;
for (int i = 1; i <= n; i++) {
int depth = dfs(i, -1);
if (depth > max_depth) {
vv1.clear();
vv1.push_back(i);
max_depth = depth;
}
else if (depth == max_depth) {
vv1.push_back(i);
}
}
for (int i = 0; i < vv1.size(); i++) {
cout << vv1[i] << endl;
}
}
return 0;
}