Tutor Man

Time limit1sMemory limit256 MB

Summary
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 11 and 66 inclusive.

The tiles are laid out in NN rows. An odd-numbered row holds NN tiles and an even-numbered row holds N−1N-1 tiles, with the even rows offset by half a tile. The figure below shows the layout when N=5N=5.

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 11 and the last is number NN. In the second row the first tile is number N+1N+1 and the last is number 2N−12N-1.

Tutor Man may start only from the first tile of the first row (tile 11), 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 NN. (1≤N≤5001 \le N \le 500)

Each of the next N2−⌊N/2⌋N^2 - \lfloor N/2 \rfloor lines contains the two numbers AiA_i and BiB_i of one tile. (1≤Ai,Bi≤61 \le A_i, B_i \le 6) AiA_i is the number on the left piece of tile ii and BiB_i 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.

Examples3

  1. Example 1

    Input
    5
    1 4
    4 5
    3 4
    5 4
    5 2
    4 2
    5 6
    4 4
    6 5
    2 4
    5 1
    6 1
    1 6
    2 3
    4 2
    5 3
    1 2
    5 5
    4 1
    2 2
    4 3
    2 3
    3 4
    
    Expected output
    7
    1 2 7 12 17 22 23
    
  2. Example 2

    Input
    3
    1 2
    2 3
    6 6
    2 4
    3 5
    6 6
    4 5
    5 6
    
    Expected output
    4
    1 2 5 8
    
  3. Example 3

    Input
    4
    1 5
    5 3
    5 5
    5 6
    5 3
    6 4
    4 5
    2 5
    2 4
    4 3
    2 4
    5 2
    1 4
    1 6
    
    Expected output
    7
    1 5 8 12 9 10 13