```/题目要求:①判断是否是树,如果是,②输出最深的根
已知N个点,N-1条边,若只有一个连通块,则是树
①并查集②dfs/
include [HTML_REMOVED]
include [HTML_REMOVED]
include [HTML_REMOVED]
include [HTML_REMOVED]
using namespace std;
const int N = 10010, M = N * 2;
int n;
int h[N], e[M], ne[M], idx;//无向图,e,ne数组要开二倍
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;
}```