Billiards Sorting

Ball 1 moves through the triangular rack by swapping with a touching ball above or below, and the task asks for the fewest swaps that sort up to 15 balls.

Medium7BFSGraphBacktrackingNo attempts yetTime limit7sMemory limit512 MB

Problem

Rotation is a pocket billiards game played with 15 balls numbered 1 to 15. At the start of a game the balls sit in a triangular rack in this order. The order is simplified from the real rules of Rotation to keep the problem short.

        [ 1]
      [ 2][ 3]
    [ 4][ 5][ 6]
  [ 7][ 8][ 9][10]
[11][12][13][14][15]

You build automatic billiards machines. Your first machine stacks the balls into the triangle, but it cannot put them in the right order.

So you are building a second machine that repairs the order by swapping balls. To keep it cheap, the machine swaps ball 1 only with a ball that touches it from the row above or the row below. Two balls in the same row are never swapped, even when they sit side by side. In the rack below the machine can perform exactly four swaps: (1,2), (1,3), (1,8), (1,9).

        [ 5]
      [ 2][ 3]
    [ 4][ 1][ 6]
  [ 7][ 8][ 9][10]
[11][12][13][14][15]

The ball in row rr, position cc from the left, touches positions c1c-1 and cc of row r1r-1, and positions cc and c+1c+1 of row r+1r+1, whenever those positions lie inside the triangle.

A rack of NN rows is in the right order when reading the rows from top to bottom, each row from left to right, gives 1,2,,N(N+1)/21, 2, \dots, N(N+1)/2. Write a program that computes the minimum number of swaps.

Input

The input holds several test cases.

The first line of a test case has one integer NN (1N51 \le N \le 5), the number of rows. The next NN lines describe the rack that the first machine stacked: line ii has exactly ii integers, the numbers of the balls in row ii from left to right. The numbers on those NN lines form a permutation of 11 through N(N+1)/2N(N+1)/2.

The last line has a single 0. Print nothing for it.

Output

For each test case, print one line Case x: y, where xx is the test case number starting from 1 and yy is the minimum number of swaps.

Every rack in the input can be put in the right order, and no rack needs more than 45 swaps.