-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathproblem4853.cpp
74 lines (66 loc) · 1.2 KB
/
problem4853.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
#include <bits/stdc++.h>
using namespace std;
int n, m;
vector<vector<int>> g;
vector<int> dist, parent;
void bfs(int start, int finish)
{
bool flag = false;
dist.resize(n + 1, -1);
parent.resize(n + 1, -1);
queue<int> q;
q.push(start);
dist[start] = 0;
while (!q.empty())
{
int v = q.front();
q.pop();
for (int i = 0; i < g[v].size(); i++)
{
int to = g[v][i];
if (dist[to] == -1)
{
q.push(to);
dist[to] = dist[v] + 1;
parent[to] = v;
}
if (to == finish)
{
flag = true;
break;
}
}
if (flag)
break;
}
}
void path(int v)
{
if (v == -1)
return;
path(parent[v]);
cout << v << ' ';
}
int main()
{
int a, b, u, v;
cin >> n >> m >> a >> b;
g.resize(n + 1);
while (m--)
{
cin >> u >> v;
g[u].push_back(v);
g[v].push_back(u);
}
bfs(a, b);
if (parent[b] == -1)
{
cout << "-1\n";
}
else
{
cout << dist[b] << '\n';
path(b);
cout << '\n';
}
}