-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathduong_di_-1.cpp
More file actions
79 lines (74 loc) · 1.36 KB
/
Copy pathduong_di_-1.cpp
File metadata and controls
79 lines (74 loc) · 1.36 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
69
70
71
72
73
74
75
76
77
78
79
#include <bits/stdc++.h>
using namespace std;
int n, m, s, t;
vector<int> adj[1005];
bool visited[1005];
int parents[1005];
void input()
{
cin >> n >> m >> s >> t;
memset(visited, 0, sizeof(visited));
memset(parents, 0, sizeof(parents));
memset(adj, 0, sizeof(adj));
for (int i = 0; i < m; i++)
{
int x, y;
cin >> x >> y;
adj[x].push_back(y);
// adj[y].push_back(x);
}
}
void bfs(int u)
{
queue<int> q;
q.push(u);
visited[u] = true;
while (!q.empty())
{
int v = q.front();
q.pop();
for (int x : adj[v])
{
if (!visited[x])
{
q.push(x);
visited[x] = true;
parents[x] = v;
}
}
}
}
void Path(int s, int t)
{
bfs(s);
if (!visited[t])
{
cout << -1;
}
else
{
vector<int> paths;
while (t != s)
{
paths.push_back(t);
t = parents[t];
}
paths.push_back(t);
reverse(paths.begin(), paths.end());
for (int &x : paths)
{
cout << x << " ";
}
}
cout << endl;
}
int main()
{
int test;
cin >> test;
while (test--)
{
input();
Path(s, t);
}
}