#include<cstdio>
#include<vector>
#include<set>
#include<algorithm>
#include<cstring>
using namespace std;
const int maxn = 10010;
int n;
bool isroot[maxn] = { false };
int father[maxn];
vector<int> G[maxn];
int findfather(int x)
{
int a = x;
while (x != father[x])
{
x = father[x];
}
while (a != father[a])
{
int z = a;
a = father[a];
father[z] = x;
}
return x;
}
void Union(int a, int b)
{
int fa = findfather(a);
int fb = findfather(b);
if (fa != fb) father[fa] = fb;
}
void init(int n)
{
for (int i = 1; i <= n; i++)
{
father[i] = i;
}
}
int maxh = 0;
int vis[maxn] = { 0 };
vector<int> temp;
set<int> ans;//存储临时和最终得到最深的结点
void dfs(int v,int height)
{
vis[v] = 1;
if (height > maxh)
{
temp.clear();
temp.push_back(v);
maxh = height;
}
else if (height == maxh) temp.push_back(v);
for (int i = 0; i < G[v].size(); i++)
{
if (vis[G[v][i]] == 0) dfs(G[v][i], height + 1);
}
}
int main()
{
int a, b;
scanf("%d", &n);
init(n);
for (int i = 0; i < n - 1; i++)
{
scanf("%d%d", &a, &b);
G[a].push_back(b);
G[b].push_back(a);
Union(a, b);
}
for (int i = 1; i <= n; i++)
{
isroot[findfather(i)] = true;
}
int count = 0;
for (int i = 1; i <= n; i++)
{
if (isroot[i] == true) count++;
}
if (count != 1) printf("Error: %d components", count);
else
{
dfs(1, 1);
for (int i = 0; i < temp.size(); i++)
{
ans.insert(temp[i]);
}
int p = temp[0];
memset(vis, 0, sizeof(vis));//注意这里要用memset再次初始化vis,用下面的方法不行
//vis[maxn] = { 0 };
temp.clear();
maxh = 0;
dfs(p, 1);
for (int i = 0; i < temp.size(); i++)
{
ans.insert(temp[i]);
}
for (set<int>::iterator it = ans.begin(); it != ans.end(); it++)
{
printf("%d\n", *it);
}
}
return 0;
}
思路真的复杂,学到了这个寻找最大根节点的方法