-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path1669 - Round Trip.cpp
More file actions
68 lines (60 loc) · 1.4 KB
/
1669 - Round Trip.cpp
File metadata and controls
68 lines (60 loc) · 1.4 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
56
57
58
59
60
61
62
63
64
65
66
67
68
#include <bits/stdc++.h>
using namespace std;
int n, m;
vector<bool> visited, v;
vector<vector<int>> adj;
queue<int> cycle;
bool find_cycle(int index, int lastIndex) {
bool foundCycle = visited[index];
v[index] = true;
visited[index] = true;
for (auto i = adj[index].begin(); !foundCycle && i != adj[index].end();
i++) {
if (*i != lastIndex) foundCycle |= find_cycle(*i, index);
}
visited[index] = false;
if (foundCycle) {
cycle.push(index);
return true;
} else {
return false;
}
}
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
cout.tie(nullptr);
cin >> n >> m;
visited.resize(n + 1, false);
v.resize(n + 1, false);
adj.resize(n + 1, vector<int>(0));
for (int i = 0; i < m; ++i) {
int a, b;
cin >> a >> b;
adj[a].push_back(b);
adj[b].push_back(a);
}
bool test = false;
for (int i = 0; !test && i < n; ++i) {
if (!v[i + 1]) test |= find_cycle(i + 1, -1);
}
if (!test)
cout << "IMPOSSIBLE\n";
else {
stack<int> tmp;
int stop = cycle.front();
tmp.push(stop);
cycle.pop();
while (!cycle.empty()) {
tmp.push(cycle.front());
if (stop == cycle.front()) break;
cycle.pop();
}
cout << tmp.size() << "\n";
while (!tmp.empty()) {
cout << tmp.top() << " ";
tmp.pop();
}
}
return 0;
}