题目链接
形式化题意
找出一固定高度 ,使得路径总代价最小:
- 每个格子 有“通过代价” ,但前提是 ,否则该格子不可通行。
- 我们要从起点 走到终点 ,只能上下左右移动。
- 路径总代价 = 路径上所有格子的 之和(包括起点和终点)。
题目思路
显然每个格子的通过代价为正数,循环遍历每个高度,每个格子看成一个节点,上下左右移动看成边。“路径上所有点权之和最小”就可以转化为“在一个有环的加权图中,从起点到终点的最小权重路径”,使用最短路解决,而因为是四向移动,边数约 ,稀疏,SPFA 解决即可。
虽然地形高度量级在 ,但最优高度一定是某个格子高度加 1(显然如果全部高于,则降低路径高度总代价一定更小),而格子数上限只有 个,仅需查找特定高度的最优路径即可。
还有不能为了换时间,找到最低路径就抛出了,因为最低路径不一定是最优路径。
hack
5 2
1 1
3 1
3 2
3 1
3 1Code
#include <bits/stdc++.h>
using namespace std;
const int INF = 1e9;
int n, m;
vector<vector<int>> a; // 地形高度
int dx[4] = {1, -1, 0, 0};
int dy[4] = {0, 0, 1, -1};
// 计算飞行高度为 h 时的最小代价
int spfa(int h) {
// dist[i][j]:到达 (i,j) 的最小代价
vector<vector<int>> dist(n, vector<int>(m, INF));
queue<pair<int,int>> q;
// 起点自身必须合法
if (a[0][0] >= h) return INF;
dist[0][0] = h - a[0][0];
q.push({0, 0});
while (!q.empty()) {
auto [x, y] = q.front(); q.pop();
for (int d = 0; d < 4; ++d) {
int nx = x + dx[d], ny = y + dy[d];
if (nx < 0 || nx >= n || ny < 0 || ny >= m) continue;
if (a[nx][ny] >= h) continue; // 高度不满足严格小于
int cost = h - a[nx][ny];
if (dist[nx][ny] > dist[x][y] + cost) {
dist[nx][ny] = dist[x][y] + cost;
q.push({nx, ny});
}
}
}
return dist[n-1][m-1];
}
int main() {
cin >> n >> m;
a.resize(n, vector<int>(m));
set<int> heights; // 存储所有不同的地形高度
for (int i = 0; i < n; ++i) {
for (int j = 0; j < m; ++j) {
cin >> a[i][j];
heights.insert(a[i][j]);
}
}
int ans = INF;
// 枚举高度 x,飞行高度取 x+1
for (int x : heights) {
ans = min(ans, spfa(x + 1));
}
cout << ans << '\n';
return 0;
}