-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path1667 - Message Route.cpp
62 lines (54 loc) · 1.25 KB
/
1667 - Message Route.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
#include <bits/stdc++.h>
using namespace std;
int n, m;
pair<vector<int>, int> v[100000 + 1];
queue<pair<int, int>> q;
stack<int> path;
void bfs(int vertex, int depth) {
if (v[vertex].second != -1) return;
v[vertex].second = depth;
if (vertex == n) {
while (vertex != 1) {
for (auto &i : v[vertex].first) {
if (v[i].second == v[vertex].second - 1) {
path.push(vertex);
vertex = i;
}
}
}
path.push(1);
while (q.size() > 1) q.pop();
} else {
for (auto &i : v[vertex].first) {
q.push(make_pair(i, depth + 1));
}
}
}
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
cout.tie(nullptr);
cin >> n >> m;
for (int i = 0; i < m; ++i) {
int a, b;
cin >> a >> b;
v[a].first.push_back(b);
v[b].first.push_back(a);
}
for (int i = 1; i <= n; ++i) v[i].second = -1;
q.push(make_pair(1, 0));
while (!q.empty()) {
bfs(q.front().first, q.front().second);
q.pop();
}
if (path.empty()) {
cout << "IMPOSSIBLE";
} else {
cout << path.size() << "\n";
while (!path.empty()) {
cout << path.top() << " ";
path.pop();
}
}
return 0;
}