跳到正文

题解

题解:P16000 [ICPC 2020 NAC] Hopscotch

0x00AC3375约 11 分钟
原文
文章信息与版本

文章信息

收录
2026年5月11日
更新
2026年5月11日
篇幅
约 11 分钟
题目
P16000

版本

  1. v2当前
  2. v1

1. 题意

在一个数字矩阵 (ai,j)n×n(a_{i,j})_{n \times n} 上玩跳格子游戏,按照 1∼k1\sim k 的自然数顺序经过对应标号的格子(找到可行解)。每一跳的代价是两个格子之间的 1-范数距离,最小化代价(找到最优解)。

2. 分析

根据题意,从 (x,y)(x,y) 跳跃到 (x′,y′)(x',y') 的代价是 ∣x−x′∣+∣y−y′∣|x-x'| + |y-y'|。

开一个数组(记为 ff)并设 f(x′,y′)f(x',y') 表示到达此处的最小代价,很容易得到维护 dp 的赋值操作:

f(x′,y′)←min⁡(f(x′,y′),f(x,y)+∣x−x′∣+∣y−y′∣)f(x',y') \leftarrow \min\Big(f(x',y'), f(x, y) + |x-x'| + |y-y'|\Big)

按照这个关系不断更新 ff 里的值即可(初始时将 ff 全部填充为无穷大)。记得特判数字不全的情况(这时候输出 −1-1)。

全局的最坏时间复杂度为 O(n4)O(n^4)。

3. 代码

C#
C++
using System;
using System.Collections.Generic;
using System.Linq;

class P16000
{
    const int N = 110;
    static long n, k;
    static long[,] a = new long[N, N];
    static long[,] dp = new long[N, N];
    static List<(long, long)>[] v = new List<(long, long)>[N * N];

    static void Main(string[] args)
    {
        string allInput = Console.In.ReadToEnd();
        string[] tokens = allInput.Split(new[] { ' ', '\r', '\n', '\t' }, StringSplitOptions.RemoveEmptyEntries);
        int ptr = 0;

        if (ptr < tokens.Length) n = Convert.ToInt64(tokens[ptr++]);
        if (ptr < tokens.Length) k = Convert.ToInt64(tokens[ptr++]);

        long inf = 0x3f3f3f3f3f3f3f3fL;
        for (int i = 0; i < N; i++)
        {
            for (int j = 0; j < N; j++)
            {
                dp[i, j] = inf;
            }
        }
        for (int i = 0; i < N * N; i++)
        {
            v[i] = new List<(long, long)>();
        }

        for (int i = 1; i <= n; i++)
        {
            for (int j = 1; j <= n; j++)
            {
                a[i, j] = Convert.ToInt64(tokens[ptr++]);
                if (a[i, j] == 1) dp[i, j] = 0;
                v[(int)a[i, j]].Add((i, j));
            }
        }
        for (int i = 2; i <= k; i++)
        {
            foreach (var jCoord in v[i - 1])
            {
                foreach (var kCoord in v[i])
                {
                    long x1 = jCoord.Item1, y1 = jCoord.Item2, x2 = kCoord.Item1, y2 = kCoord.Item2;
                    dp[x2, y2] = Math.Min(dp[x2, y2], dp[x1, y1] + Math.Abs(x1 - x2) + Math.Abs(y1 - y2));
                }
            }
        }
        long ans = 2147483647;
        foreach (var coord in v[(int)k])
        {
            ans = Math.Min(ans, dp[coord.Item1, coord.Item2]);
        }
        if (ans == 2147483647)
        {
            Console.Write("-1");
            return;
        }
        Console.Write(ans);
    }
}
Python
C++
import sys

def solve():
    input_data = sys.stdin.read().split()
    if not input_data:
        return
    iterator = iter(input_data)
    try:
        n = int(next(iterator))
        k = int(next(iterator))
    except StopIteration:
        return
    positions = [[] for _ in range(k + 1)]
    for i in range(n):
        for j in range(n):
            val = int(next(iterator))
            positions[val].append((i, j))
    for v in range(1, k + 1):
        if not positions[v]:
            print(-1)
            return
    costs = [0] * len(positions[1])
    for v in range(1, k):
        curr_pos = positions[v]
        next_pos = positions[v + 1]
        INF = 10**9
        next_costs = [INF] * len(next_pos)
        next_r = [p[0] for p in next_pos]
        next_c = [p[1] for p in next_pos]
        for i, (r1, c1) in enumerate(curr_pos):
            base_cost = costs[i]
            for j in range(len(next_pos)):
                dist = abs(r1 - next_r[j]) + abs(c1 - next_c[j])
                new_cost = base_cost + dist
                if new_cost < next_costs[j]:
                    next_costs[j] = new_cost
        costs = next_costs
    print(min(costs))

if __name__ == "__main__":
    solve()

4. 轶事

如果把题目里的 1-范数换成 kk-范数,该怎么做?

将转移方程替换成下面的就可以了

f(x′,y′)←min⁡(f(x′,y′),f(x,y)+(∣x−x′∣k+∣y−y′∣k)1/k)f(x',y') \leftarrow \min\Big(f(x',y'), f(x, y) + (|x-x'|^k+|y-y'|^k)^{1/k}\Big)

记得把数组开成浮点数。

按照大家玩跳房子游戏的习惯,应该是习惯使用 2-范数的。换成 2-范数的话,第一组样例的答案应该是 3+2≈4.41421363+\sqrt{2} \approx 4.4142136。

参考代码
Python
import sys
import math

def solve() -> None:
    input_data = sys.stdin.read().split()
    if not input_data:
        return

    iterator = iter(input_data)
    try:
        n = int(next(iterator))
        k = int(next(iterator))
    except StopIteration:
        return

    positions = [[] for _ in range(k + 1)]

    for i in range(n):
        for j in range(n):
            val = int(next(iterator))
            positions[val].append((i, j))

    for v in range(1, k + 1):
        if not positions[v]:
            print("-1")
            return
    costs = [0.0] * len(positions[1])
    for v in range(1, k):
        curr_pos = positions[v]
        next_pos = positions[v + 1]

        INF = float('inf')
        next_costs = [INF] * len(next_pos)
        next_r = [p[0] for p in next_pos]
        next_c = [p[1] for p in next_pos]

        for i, (r1, c1) in enumerate(curr_pos):
            base_cost = costs[i]
            for j in range(len(next_pos)):
                # 2-范数距离
                dist = math.hypot(r1 - next_r[j], c1 - next_c[j])
                new_cost = base_cost + dist
                if new_cost < next_costs[j]:
                    next_costs[j] = new_cost

        costs = next_costs
    print(f"{min(costs):.6f}")

if __name__ == "__main__":
    solve()
推广到 pp 维

迭代操作和二维的公式类似,但是顺着本题解的思路来,时间复杂度会膨胀到 O(n2p)O(n^{2p})。

这也说明本题解略显暴力的 dp 方式在高维面前存在局限性。

原文