#P16000. [ICPC 2020 NAC] Hopscotch

[ICPC 2020 NAC] Hopscotch

题目描述

There’s a new art installation in town, and it inspires you... to play a childish game. The art installation consists of a floor with an n×nn \times n matrix of square tiles. Each tile holds a single number from 11 to kk. You want to play hopscotch on it. You want to start on some tile numbered 11, then hop to some tile numbered 22, then 33, and so on, until you reach some tile numbered kk. You are a good hopper, so you can hop any required distance. You visit exactly one tile of each number from 11 to kk.

What’s the shortest possible total distance over a complete game of Hopscotch? Use the Manhattan distance: the distance between the tile at (x1,y1)(x_1, y_1) and the tile at (x2,y2)(x_2, y_2) is x1x2+y1y2|x_1 - x_2| + |y_1 - y_2|.

输入格式

The first line of input contains two space-separated integers nn (1n501 \le n \le 50) and kk (1kn21 \le k \le n^2), where the art installation consists of an n×nn \times n matrix with tiles having numbers from 11 to kk.

Each of the next nn lines contains nn space-separated integers xx (1xk1 \le x \le k). This is the art installation.

输出格式

Output a single integer, which is the total length of the shortest path starting from some 11 tile and ending at some kk tile, or 1-1 if it isn’t possible.

10 5
5 1 3 4 2 4 2 1 2 1
4 5 3 4 1 5 3 1 1 4
4 2 4 1 5 4 5 2 4 1
5 2 1 5 5 3 5 2 3 2
5 5 2 3 2 3 1 5 5 5
3 4 2 4 2 2 4 4 2 3
1 5 1 1 2 5 4 1 5 3
2 2 4 1 2 5 1 4 3 5
5 3 2 1 4 3 5 2 3 1
3 4 2 5 2 5 3 4 4 2
5
10 5
5 1 5 4 1 2 2 4 5 2
4 2 1 4 1 1 1 5 2 5
2 2 4 4 4 2 4 5 5 4
2 4 4 5 5 5 2 5 5 2
2 2 4 4 4 5 4 2 4 4
5 2 5 5 4 1 2 4 4 4
4 2 1 2 4 4 1 2 4 5
1 2 1 1 2 4 4 1 4 5
2 1 2 5 5 4 5 2 1 1
1 1 2 4 5 5 5 5 5 5
-1