Path Reconstruction
View as PDFYou are given an undirected graph with vertices and
edges, as well as two vertices
and
.
Find the lexicographically smallest shortest path from to
. Paths are compared as vertex
sequences: at the first position where two paths differ, the path with the smaller vertex number is
lexicographically smaller.
To make the required path deterministic, sort each adjacency list in increasing order and run BFS
from , storing the first parent used to reach each vertex.
Input
The first line contains four integers ,
,
, and
.
The next lines each contain two integers
and
, meaning there is an undirected edge
between vertices
and
.
Vertices are numbered from to
.
Output
If is unreachable from
, print
-1.
Otherwise, print two lines. The first line should contain , the number of edges in the path. The
second line should contain
integers, the vertices of the path from
to
.
Constraints
Example 1
Input
6 7 1 6
1 2
1 3
2 4
3 4
4 6
2 5
5 6
Output
3
1 2 4 6
Explanation
There are multiple shortest paths from to
, including
[1, 2, 4, 6] and [1, 2, 5, 6].
The path [1, 2, 4, 6] is lexicographically smallest.
Example 2
Input
5 3 1 5
1 2
2 3
4 5
Output
-1
Explanation
Vertex is not reachable from vertex
.
Comments