-
Notifications
You must be signed in to change notification settings - Fork 0
/
1021.cpp
70 lines (58 loc) · 1.41 KB
/
1021.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
#include <cstdio>
#include <vector>
#include <cstring>
#include <set>
#include <algorithm>
const int MAXN = 10000 + 5;
std::vector<int> g[MAXN];
bool vis[MAXN];
int depth[MAXN];
void dfs(int n, int x, int cnt, int &maxDepth) {
depth[x] = cnt;
vis[x] = true;
maxDepth = std::max(cnt, maxDepth);
for (auto ch : g[x]) {
if (!vis[ch]) dfs(n, ch, cnt + 1, maxDepth);
}
}
int main() {
int n;
scanf("%d", &n);
for (int i = 0; i < n - 1; i++) {
int u, v;
scanf("%d%d", &u, &v);
g[u].push_back(v);
g[v].push_back(u);
}
int cnt = 0;
int maxDepth = 0;
for (int i = 1; i <= n; i++) {
if (!vis[i]) {
dfs(n, i, 0, maxDepth);
cnt++;
}
}
if (cnt > 1) {
printf("Error: %d components", cnt);
} else {
std::set<int> ans;
for (int i = 1; i <= n; i++) {
if (depth[i] == maxDepth) {
ans.insert(i);
}
}
int x = *ans.begin();
memset(vis, false, sizeof(vis));
memset(depth, 0, sizeof(depth));
dfs(n, x, 0, maxDepth);
for (int i = 1; i <= n; i++) {
if (depth[i] == maxDepth) {
ans.insert(i);
}
}
for (auto &x : ans) {
printf("%d\n", x);
}
}
return 0;
}