-
Notifications
You must be signed in to change notification settings - Fork 0
/
A1021-1.cpp
93 lines (85 loc) · 1.53 KB
/
A1021-1.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
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
/*
* author: zhouyuhao
* created: 2023-03-30 13:46:48
* modified: 2023-03-30 14:31:26
* item: Programming Ability Test
* site: Yuting
*/
#include <iostream>
#include <numeric>
#include <set>
#include <vector>
using namespace std;
int maxl = -1;
vector<bool> vis;
vector<int> f, temp;
set<int> ans;
vector<vector<int>> g;
void dfs(int s, int l) {
vis[s] = true;
if (l > maxl) {
maxl = l;
temp.clear();
temp.emplace_back(s);
} else if (l == maxl) {
temp.emplace_back(s);
}
for (int i = 0; i < (int)g[s].size(); i++) {
if (!vis[g[s][i]]) {
dfs(g[s][i], l + 1);
}
}
}
int find(int x) {
int a = x;
while (x != f[x]) {
x = f[x];
}
while (a != f[a]) {
int z = a;
a = f[a], f[z] = x;
}
return x;
}
void joint(int a, int b) {
int fa = find(a), fb = find(b);
if (fa != fb) {
f[fa] = fb;
}
}
int main(int argc, char const *argv[]) {
int n;
cin >> n;
g.resize(n + 1), f.resize(n + 1);
iota(f.begin(), f.end(), 0);
vis.resize(n + 1, false);
for (int i = 0; i < n - 1; i++) {
int s, e;
cin >> s >> e;
g[s].emplace_back(e);
g[e].emplace_back(s);
joint(s, e);
}
int cnt = 0;
for (int i = 1; i <= n; i++) {
int fi = find(i);
if (!vis[fi]) {
++cnt;
vis[fi] = true;
}
}
if (cnt == 1) {
fill(vis.begin(), vis.end(), false);
dfs(1, 1);
set<int> ans(temp.begin(), temp.end());
fill(vis.begin(), vis.end(), false);
dfs(temp[0], 1);
ans.insert(temp.begin(), temp.end());
for (auto it : ans) {
cout << it << "\n";
}
} else {
cout << "Error: " << cnt << " components\n";
}
return 0;
}