아직 만들고 있는 페이지입니다.

이 페이지는 아직 만드는 중입니다. 보이는 내용은 바뀔 수 있습니다.

Hopscotch 500

시간 제한2초메모리 제한1024 MB

요약
1부터 k까지 번호가 붙은 n x n 격자에서 1에서 시작해 k까지 순서대로 이동하며, 두 좌표 차이 제곱의 최솟값으로 정의된 거리의 합을 최소화한다.
난이도

보통10점 중 7점

유형
동적 계획법, 기하
정답자
아직 제출이 없습니다

문제

Do you remember the new art installation from NAC 2020? Well, that artist is at it again, on a grander scale this time, and the new artwork still inspires you---to play a childish game. The art installation consists of a floor with a square matrix of 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 a tile numbered 22, then 33, and so on, until you reach a tile numbered kk.

Instead of the usual Euclidean distance, define the distance between the tile at (x_1,y_1)(x\_1,y\_1) and the tile at (x_2,y_2)(x\_2,y\_2) as: \[\min\left[(x_1-x_2)^2, (y_1-y_2)^2\right]\] You want to hop the shortest total distance overall, using this new distance metric. Note that a path with no hops is still a path, and has length 00. What is the length of the shortest path?

입력

The first line of input contains two space-separated integers nn (1≤n≤5001 \le n \le 500) and kk (1≤k≤n21\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 (1≤x≤k1 \le x \le k). These are the numbers in the art installation.

출력

Output a single integer, which is the total length of the shortest path from any 11 tile to any kk tile using our distance metric, or −1-1 if no such path exists.

예제2

  1. 예제 1

    입력
    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
    
    예상 출력
    0
    
  2. 예제 2

    입력
    10 30
    18 13 30 15 18 16 14 1 5 5
    17 18 7 30 14 30 13 14 1 28
    28 24 7 23 9 10 5 12 21 6
    11 16 6 2 27 14 1 26 7 21
    16 2 9 26 6 24 22 12 8 16
    17 28 29 19 4 6 21 19 6 22
    11 27 11 26 13 23 10 3 18 6
    14 19 9 8 17 6 16 22 24 1
    12 19 10 21 1 8 20 24 29 21
    21 29 1 23 23 24 6 20 25 17
    
    예상 출력
    19