a392中等最小瓶頸路徑・限制邊的 BFS
APCS 2022/10:蓋步道 (ZeroJudge j125)
先求最小可能的最大相鄰高度差,再於該限制下求最短步數。
這題在學什麼
把格子當節點,相鄰邊權為高度差絕對值。第一階段用 Dijkstra 的形式求瓶頸:best[v] 表示到 v 的最小可能最大邊權,從 u 經權重 w 的邊延伸時,新候選是 max(best[u],w),而不是兩者相加。最小堆積優先佇列每次取出瓶頸最小者,抵達終點時便得到最小限制 D。
此更新具有單調性:延伸路徑不會讓瓶頸降低,因此 Dijkstra 的確定最小值論證仍成立。接著只允許高度差≤D 的邊,對整張圖另做一次 BFS;每條邊代表一步,BFS 第一次到終點的距離就是達到最優瓶頸下的最少步數。
兩個目標必須分兩階段。到某中繼格時瓶頸較小但步數較多的路,往後可能被更大的邊權蓋過優勢,這時原本瓶頸稍大卻較短的路反而較好。不能只在第一階段為每格保留一組 (瓶頸,步數) 就認為次要目標也已最佳化。N=1 時起終點相同,兩階段都得到 0。
Step-by-step animation
示意:2×2 高度 [1,10] / [3,4]
步驟 1 / 3
起點初始化
起點瓶頸為 0,右邊邊權 9,下邊邊權 2。
1:best0
10:best9
3:best2
4:未到達
- 佇列
- (2,左下),(9,右上)
#include <bits/stdc++.h>
using namespace std;
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
int n;
cin >> n;
int size = n * n;
vector<int> height(size), best(size, INT_MAX);
for (int &x : height)
cin >> x;
int dr[] = {-1, 0, 1, 0}, dc[] = {0, 1, 0, -1};
priority_queue<pair<int, int>, vector<pair<int, int>>, greater<pair<int, int>>> heap;
best[0] = 0;
heap.push({0, 0});
while (!heap.empty()) {
auto [cost, u] = heap.top();
heap.pop();
if (cost != best[u])
continue;
if (u == size - 1)
break;
for (int d = 0; d < 4; ++d) {
int r = u / n + dr[d], c = u % n + dc[d];
if (r < 0 || r >= n || c < 0 || c >= n)
continue;
int v = r * n + c;
int candidate = max(cost, abs(height[u] - height[v]));
if (candidate < best[v]) {
best[v] = candidate;
heap.push({candidate, v});
}
}
}
int limit = best.back();
vector<int> distance(size, -1);
queue<int> ready;
ready.push(0);
distance[0] = 0;
while (!ready.empty()) {
int u = ready.front();
ready.pop();
if (u == size - 1)
break;
for (int d = 0; d < 4; ++d) {
int r = u / n + dr[d], c = u % n + dc[d];
if (r < 0 || r >= n || c < 0 || c >= n)
continue;
int v = r * n + c;
if (distance[v] == -1 && abs(height[u] - height[v]) <= limit) {
distance[v] = distance[u] + 1;
ready.push(v);
}
}
}
cout << limit << '\n' << distance.back() << '\n';
}先試著自己完成,再切換語言比對解法。參考程式可複製到題目編輯器。