CF677D.Vanya and Treasure

提高+/省选-

通过率:0%

时间限制:1.50s

内存限制:256MB

AC君温馨提醒

该题目为【codeforces】题库的题目,您提交的代码将被提交至codeforces进行远程评测,并由ACGO抓取测评结果后进行展示。由于远程测评的测评机由其他平台提供,我们无法保证该服务的稳定性,若提交后无反应,请等待一段时间后再进行重试。

题目描述

Vanya is in the palace that can be represented as a grid n × m. Each room contains a single chest, an the room located in the i-th row and j-th columns contains the chest of type a__ij. Each chest of type x ≤ p - 1 contains a key that can open any chest of type x + 1, and all chests of type 1 are not locked. There is exactly one chest of type p and it contains a treasure.

Vanya starts in cell (1, 1) (top left corner). What is the minimum total distance Vanya has to walk in order to get the treasure? Consider the distance between cell (_r_1, _c_1) (the cell in the row _r_1 and column _c_1) and (_r_2, _c_2) is equal to |_r_1 - _r_2| + |_c_1 - _c_2|.

万尼亚位于一个 n×mn \times m 的宫殿网格中。每个房间内恰好有一只宝箱,位于第 ii 行、第 jj 列的房间中存放着类型为 aija_{ij} 的宝箱。对于任意类型 x≤p−1x \leq p-1 的宝箱,其中均含有一把钥匙,可开启任意类型为 x+1x+1 的宝箱;而所有类型为 11 的宝箱均未上锁。恰好存在一只类型为 pp 的宝箱,其中藏有宝藏。

万尼亚从单元格 (1, 1)(1,\,1)(左上角)出发。他为取得宝藏所需行走的最小总距离是多少?定义单元格 (r1, c1)(r_1,\,c_1)(即第 r1r_1 行、第 c1c_1 列的单元格)与 (r2, c2)(r_2,\,c_2) 之间的距离为 ∣r1−r2∣+∣c1−c2∣|r_1 - r_2| + |c_1 - c_2|。

输入格式

The first line of the input contains three integers n, m and p (1 ≤ n, m ≤ 300, 1 ≤ p ≤ n·m) — the number of rows and columns in the table representing the palace and the number of different types of the chests, respectively.

Each of the following n lines contains m integers a__ij (1 ≤ a__ij ≤ p) — the types of the chests in corresponding rooms. It's guaranteed that for each x from 1 to p there is at least one chest of this type (that is, there exists a pair of r and c, such that a__rc = x). Also, it's guaranteed that there is exactly one chest of type p.

输入的第一行包含三个整数 nn、mm 和 pp(1 ≤ n, m ≤ 3001 ≤ n, m ≤ 300,1 ≤ p ≤ n ⋅ m1 ≤ p ≤ n · m),分别表示代表宫殿的表格的行数、列数以及宝箱类型的总数。

接下来的 nn 行中,每行包含 mm 个整数 aija_{ij}(1 ≤ aij ≤ p1 ≤ a_{ij} ≤ p),表示对应房间中宝箱的类型。保证对每个从 11 到 pp 的整数 xx,至少存在一个类型为 xx 的宝箱(即存在一对 rr 和 cc,使得 arc = xa_{rc} = x)。此外,还保证恰好存在一个类型为 pp 的宝箱。

输出格式

Print one integer — the minimum possible total distance Vanya has to walk in order to get the treasure from the chest of type p.

输出一个整数——Vanya 为从类型为 p 的宝箱中获取宝藏所需行走的最小总距离。

输入输出样例

  • 输入#1

    3 4 3
    2 1 1 1
    1 1 1 1
    2 1 1 3

    输出#1

    5
  • 输入#2

    3 3 9
    1 3 5
    8 9 7
    4 6 2

    输出#2

    22
  • 输入#3

    3 4 12
    1 2 3 4
    8 7 6 5
    9 10 11 12

    输出#3

    11

输入解题思路,AI测评打分。不知道怎么写?

首页