Tutor Man
Time limit1sMemory limit256 MB
On a honeycomb of domino tiles where only matching numbers can be crossed, find the shortest path from tile 1 to the last tile of the last row.
- Level
Medium7 of 10
- Topics
- BFS, Graph, Implementation
- Solved
- No attempts yet
Problem
Tutor Man has arrived at an ancient Mayan temple to recover his stolen tutoring notes. The notes lie on the far side of the temple entrance, but a deep cliff separates the two sides. Just then, giant domino tiles fall from the sky and form a bridge across the cliff.
Each domino tile is divided into two square pieces, and each piece bears a number between and inclusive.
The tiles are laid out in rows. An odd-numbered row holds tiles and an even-numbered row holds tiles, with the even rows offset by half a tile. The figure below shows the layout when .

To step from one tile to another, the two tiles must be adjacent, and the two pieces that share the touching edge must hold the same number.
Tiles are numbered in row-major order. In the first row the first tile is number and the last is number . In the second row the first tile is number and the last is number .
Tutor Man may start only from the first tile of the first row (tile ), and the notes rest on the last tile of the last row. Find the path from the first tile to the last tile of the last row that passes through the fewest tiles.
If the last tile of the last row cannot be reached, the destination becomes the tile with the largest number among all tiles reachable from the first tile.
Input
The first line contains . ()
Each of the next lines contains the two numbers and of one tile. () is the number on the left piece of tile and is the number on the right piece. Tiles are given in increasing order of their number.
Output
On the first line, print the length of the shortest path (the number of tiles it passes through).
On the second line, print the numbers of the tiles on that path in order, separated by spaces. If several shortest paths exist, print the lexicographically smallest one, comparing the sequences of tile numbers position by position.