#include<iostream>
#include<set>
#include<vector>
#include<cstdio>
using namespace std;
const int maxn = 10005;
set<int> G[maxn];
bool marked[maxn]{ 0 };
int component = 0, depth = 0, max_depth = 0, cur_root;
set<int> deepest, deepest1;
void dfs_s(int v, set<int> &deepest) {
marked[v] = true;
bool flag = false;
depth++;
if (depth > max_depth) {
deepest.clear();
deepest.insert(v);
max_depth = depth;
}
else if (depth == max_depth)
deepest.insert(v);
for (auto w : G[v]) {
if (!marked[w]) {
dfs_s(w, deepest);
flag = true;
}
}
depth--;
}
int main() {
int n;
scanf("%d", &n);
int v, w;
for (int i = 0; i < n - 1; i++) {
scanf("%d%d", &v, &w);
G[v].insert(w);
G[w].insert(v);
}
for (int i = 1; i <= n; i++) {
if (!marked[i]) {
component++;
dfs_s(i, deepest);
}
}
if (component > 1) printf("Error: %d components", component);//Error: K components
else {
for (auto i : deepest) deepest1.insert(i);
fill(marked, marked + n + 1, false);
depth = 0;max_depth = 0;
dfs_s(*(deepest.begin()), deepest1);
for (auto i : deepest) deepest1.insert(i);
for (auto p : deepest1) printf("%d\n", p);
}
system("pause");
return 0;
}
测试数据集
// 1应当返回1
1
5
1 2
1 3
1 4
1 5
5
1 2
2 3
3 4
4 5
6
1 2
1 3
1 4
2 5
4 6
// 和测试点4,5相关, 第一轮搜索的多个最深点,两两之间不一定最深,但是在第二轮搜索中是可以相互替代的, 所以他们都会出现在最终的点集中
6
1 2
1 3
3 4
4 5
4 6
*/