跳到正文

个人记录

CodeForces 1353F

skimlight约 5 分钟
原文
文章信息与版本

文章信息

发布
2026年9月22日
收录
2026年9月23日
更新
2026年11月14日
篇幅
约 5 分钟

版本

  1. v1当前

结论:至少有一个点高度不变。
证明:假设最优路径上所有点的高度组成的序列被修改为:x,x+1,…,x+len−1x, x + 1, \dots ,x + len - 1,那序列:x+1,x+2,…x+lenx + 1, x + 2, \dots x + len 一定更优,矛盾。

枚举不变的点,以固定高度。

那需要考虑的因素有:

  1. 当前的位置
  2. 操作次数(最优化属性)

定义:fi,jf_{i, j} 表示从 (1,1)(1, 1) 走到 (i,j)(i, j) 的最小操作次数。gi,jg_{i, j} 表示从 (i,j)(i, j) 走到 (n,m)(n, m) 的最小操作次数。其中 (i,j)(i, j) 为枚举的高度不变的点。

特殊处理一下和 (i,j)(i, j) 在同一行和同一列的点。

每个 (i,j)(i, j) 的答案就是 f1,1+gn,mf_{1, 1} + g_{n, m}

C++
#include<bits/stdc++.h>
using namespace std;
using ll = long long;
const int N = 105;
const ll inf = 1e18;
int n, m;
ll a[N][N], dp1[N][N], dp2[N][N], ans = inf;
ll dist(int ax, int ay, int bx, int by) {
    return (abs(ax - bx) + abs(ay - by));
}
void work(int sx, int sy) {
    for (int i = 0; i <= n; ++ i) {
        for (int j = 0; j <= m; ++ j) {
            dp1[i][j] = dp2[i][j] = inf;
        }
    }
    dp1[sx][sy] = dp2[sx][sy] = 0;
    for (int i = sx - 1; i >= 1; -- i) {
        ll cnt = a[i][sy] - a[sx][sy] + dist(i, sy, sx, sy);
        if (cnt >= 0) {
            dp1[i][sy] = dp1[i + 1][sy] + cnt;
        }
    }
    for (int j = sy - 1; j >= 1; -- j) {
        ll cnt = a[sx][j] - a[sx][sy] + dist(sx, j, sx, sy);
        if (cnt >= 0) {
            dp1[sx][j] = dp1[sx][j + 1] + cnt;
        }
    }
    for (int i = sx - 1; i >= 1; -- i) {
        for (int j = sy - 1; j >= 1; -- j) {
            ll cnt = a[i][j] - a[sx][sy] + dist(i, j, sx, sy);
            if (cnt >= 0) {
                dp1[i][j] = min(dp1[i + 1][j], dp1[i][j + 1]) + cnt;
            }
        }
    }
    for (int i = sx + 1; i <= n; ++ i) {
        ll now = a[i][sy] - (a[sx][sy] + dist(i, sy, sx, sy));
        if (now >= 0) {
            dp2[i][sy] = dp2[i - 1][sy] + now;
        }
    }
    for (int i = sy + 1; i <= m; ++ i) {
        ll now = a[sx][i] - (a[sx][sy] + dist(sx, i, sx, sy));
        if (now >= 0) {
            dp2[sx][i] = dp2[sx][i - 1] + now;
        }
    }
    for (int i = sx + 1; i <= n; ++ i) {
        for (int j = sy + 1; j <= m; ++ j) {
            ll cnt = a[i][j] - (a[sx][sy] + dist(i, j, sx, sy));
            if (cnt >= 0) {
                dp2[i][j] = min(dp2[i - 1][j], dp2[i][j - 1]) + cnt;
            }
        }
    }
    ans = min(ans, dp1[1][1] + dp2[n][m]);
}
void solve() {
    cin >> n >> m;
    for (int i = 1; i <= n; ++ i) {
        for (int j = 1; j <= m; ++ j) {
            cin >> a[i][j];
        }
    }
    ans = inf;
    if (n == 1 && m == 1) {
        cout << "0\n";
        return ;
    }
    for (int i = 1; i <= n; ++ i) {
        for (int j = 1; j <= m; ++ j) {
            work(i, j);
        }
    }
    cout << ans << "\n";
}
int main() {
    ios::sync_with_stdio(false), cin.tie(0);
    int T;
    cin >> T;
    while (T --) {
        solve();
    }
    return 0;
}
原文