atcoder#ABC224D. [ABC224D] 8 Puzzle on Graph
[ABC224D] 8 Puzzle on Graph
Score : points
Problem Statement
Takahashi found a puzzle along some road. It is composed of an undirected graph with nine vertices and edges, and eight pieces.
The nine vertices of the graph are called Vertex , Vertex , , Vertex . For each , the -th edge connects Vertex and Vertex . The eight pieces are called Piece , Piece , , Piece . For each , Piece is on Vertex . Here, it is guaranteed that all pieces are on distinct vertices. Note that there is exactly one empty vertex without a piece.
Takahashi can do the following operation on the puzzle any number of times (possibly zero).
Choose a piece on a vertex adjacent to the empty vertex, and move it to the empty vertex.
By repeating this operation, he aims to complete the puzzle. The puzzle is considered complete when the following holds.
- For each , Piece is on Vertex .
Determine whether it is possible for Takahashi to complete the puzzle. If it is possible, find the minimum number of operations needed to do so.
Constraints
- The given graph has no multi-edges or self-loops.
- All values in input are integers.
Input
Input is given from Standard Input in the following format:
Output
If it is possible for Takahashi to complete the puzzle, find the minimum number of operations needed to do so. Otherwise, print .
5
1 2
1 3
1 9
2 9
3 9
3 9 2 4 5 6 7 8
5
The following procedure completes the puzzle in five operations.
- Move Piece from Vertex to Vertex .
- Move Piece from Vertex to Vertex .
- Move Piece from Vertex to Vertex .
- Move Piece from Vertex to Vertex .
- Move Piece from Vertex to Vertex .
On the other hand, it is impossible to complete the puzzle in less than five operations. Thus, we should print . Note that the given graph may not be connected.
5
1 2
1 3
1 9
2 9
3 9
1 2 3 4 5 6 7 8
0
The puzzle is already complete from the beginning. Thus, the minimum number of operations needed to complete the puzzle is .
12
8 5
9 6
4 5
4 1
2 5
8 9
2 1
3 6
8 7
6 5
7 4
2 3
1 2 3 4 5 6 8 7
-1
No sequence of operations can complete the puzzle, so we should print .
12
6 5
5 4
4 1
4 7
8 5
2 1
2 5
6 9
3 6
9 8
8 7
3 2
2 3 4 6 1 9 7 8
16