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 (≤104) 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 <cstring>
#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;
const int N = 10010, M = N * 2;
int n;
int h[N], e[M], ne[M], idx;
int p[N];
int find(int x)
{
if (p[x] != x) p[x] = find(p[x]);
return p[x];
}
void add(int a, int b)
{
e[idx] = b, ne[idx] = h[a], h[a] = idx ++ ;
}
int dfs(int u, int father)
{
int depth = 0;
for (int i = h[u]; ~i; i = ne[i])
{
int j = e[i];
if (j == father) continue;
depth = max(depth, dfs(j, u) + 1);
}
return depth;
}
int main()
{
cin >> n;
memset(h, -1, sizeof h);
for (int i = 1; i <= n; i ++ ) p[i] = i;
int k = n;
for (int i = 0; i < n - 1; i ++ )
{
int a, b;
cin >> a >> b;
if (find(a) != find(b))
{
k -- ;
p[find(a)] = find(b);
}
add(a, b), add(b, a);
}
if (k > 1) printf("Error: %d components", k);
else
{
vector<int> nodes;
int max_depth = -1;
for (int i = 1; i <= n; i ++ )
{
int depth = dfs(i, -1);
if (depth > max_depth)
{
max_depth = depth;
nodes.clear();
nodes.push_back(i);
}
else if (depth == max_depth)
nodes.push_back(i);
}
for (auto v : nodes) cout << v << endl;
}
return 0;
}
题意是先输入一个数字n,然后输入n-1行边。如果这些边组成的图的连通分量大于1,就输出error,并指出有多少个连通分量,如果只有一个连通分量,要求求出从最深的根,即从如果某点作为树的根结点,这颗树的高度最大,满足条件的点可能不止一个,要把满足条件的点全部输出。
思路是首先设置初始连通分量为n,然后输入n-1行组成边的两个点,用并查集(https://www.acwing.com/problem/content/838/)来判断是否这两个点是否处于同一集合,如果不在同一个集合,就将连通分量数减1。同时在邻接表中添加a与b的关系。
如果连通分量等于1,然后遍历每一个点,用深度优先遍历求出以这个点为根的话,树的最大深度。然后进行比较,留下深度最大的那几个点。