-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathEulerTour.cpp
More file actions
55 lines (55 loc) · 1.16 KB
/
EulerTour.cpp
File metadata and controls
55 lines (55 loc) · 1.16 KB
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
// Euler Path/Circuit on undirected graph (Hierholzer, multiset version)
// Handles both Euler circuit (all even degree) and Euler path (exactly 2 odd degree)
int n;
multiset<int>g[505];
vector<int>ans;
void dfs(int now) {
while (g[now].size()) {
int x = *g[now].begin();
g[now].erase(g[now].lower_bound(x));
g[x].erase(g[x].lower_bound(now));
dfs(x);
}
ans.push_back(now);
}
void solve() {
ans.clear();
for (int i = 1; i <= 500; i++) {
g[i].clear();
}
for (int i = 0; i < n; i++) {
int x, y;
cin >> x >> y;
g[x].insert(y);
g[y].insert(x);
}
int x = 0, y = 0;
for (int i = 1; i <= 500; i++) {
if (g[i].size() % 2 == 1) {
if (x == 0) {
x = i;
}
else {
y = i;
}
}
}
if (!x) {
dfs(1);
}
else {
dfs(min(x, y));
}
reverse((ans).begin(), (ans).end());
for (auto &i : ans) {
cout << i << '\n';
}
cout << '\n';
}
int main(){
ios_base::sync_with_stdio(0);
cin.tie(0);
while (cin >> n && n) {
solve();
}
}