b058中等

107 臺北市資訊學科能力競賽(2018)|勇者冒險(Adventure)

最小化路徑中最大怪物等級。

解題思路

把可通行格建成四鄰接圖,其餘未列格子是沙漠。起終點權值設0。

維護dist[v]為從起點到v的最小所需等級;沿邊進入v時候選為max(dist[u],level[v])。用最小堆取最小候選,類似Dijkstra。

max運算不會讓路徑代價下降,因此當最小距離節點出堆時,不可能被更晚處理的較大代價路徑改善;出堆目的地即可回傳。

V=RC,時間 O(V log V),圖、距離、堆 O(V);Python輸入另O(N)。

Step-by-step animation

最小瓶頸 Dijkstra|1×3地圖,起終點在兩端,中間等級7。

回報動畫錯誤
步驟 1 / 3

起點

1×3地圖,起終點在兩端,中間等級7。

S:0
7
T:0
distS
0

Reference solution

回報程式錯誤

完整程式

#include <bits/stdc++.h>
using namespace std;
int main() {
    int r, c, sx, sy, tx, ty, n;
    cin >> r >> c >> sx >> sy >> tx >> ty >> n;
    int V = r * c, S = sx * c + sy, T = tx * c + ty;
    vector<int> a(V, -1), d(V, INT_MAX);
    while (n--) {
        int x, y, l;
        cin >> x >> y >> l;
        a[x * c + y] = l;
    }
    a[S] = a[T] = 0;
    priority_queue<pair<int, int>, vector<pair<int, int>>, greater<pair<int, int>>> q;
    d[S] = 0;
    q.push({0, S});
    while (q.size()) {
        auto [w, u] = q.top();
        q.pop();
        if (w != d[u])
            continue;
        if (u == T) {
            cout << w << "\n";
            break;
        }
        int x = u / c, y = u % c;
        for (auto [dx, dy] : vector<pair<int, int>>{{1, 0}, {-1, 0}, {0, 1}, {0, -1}}) {
            int xx = x + dx, yy = y + dy;
            if (xx < 0 || xx >= r || yy < 0 || yy >= c)
                continue;
            int v = xx * c + yy;
            if (a[v] < 0)
                continue;
            int z = max(w, a[v]);
            if (z < d[v]) {
                d[v] = z;
                q.push({z, v});
            }
        }
    }
}

先試著自己完成,再切換語言比對解法。參考程式可複製到題目編輯器。

更多