#include <iostream>
#include <cstring>
#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]);//如果该节点没有父节点那么该节点p[x] == 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();//vector的删除操作更新最大深度
nodes.push_back(i);
}
else if (depth == max_depth)//否则就进入vector数组
nodes.push_back(i);
}
for(auto v : nodes) cout << v << endl;
}
return 0;
}
PAT 甲级 求二叉树最深的根
最新推荐文章于 2022-07-28 22:22:05 发布
![](https://img-home.csdnimg.cn/images/20240711042549.png)