a754困難最大瓶頸路徑的 Dijkstra

CPE:Heavy Cargo (UVa 544)

用 max–min 轉移求可運送的最大重量。

前往題目練習 →回報教學錯誤n≤200,矩陣版時間 O(n²+r)、空間 O(n²)。

解題思路

路徑可載重量等於沿路最小邊權;多條路徑之間則取最大。令 best[v] 為目前找到從起點到 v 的最大瓶頸值,起點設為無限大。延伸一條限重 w 的邊時,候選值是 min(best[u],w),比 best[v] 大才更新。

每次選未確定節點中 best 最大者。任何經過其餘未確定點的繞路,瓶頸不會超過這個最大值,因此該點可立即確定,與最短路 Dijkstra 的論證對應。矩陣保留平行邊較大的限重。讀到 0 0 結束,Scenario #x 後接重量 tons,再印空行;零限重道路也可表示為容量 0。

Step-by-step animation

示意:AB=100,BC=80,AC=50

回報動畫錯誤
步驟 1 / 3

從 A 出發

先得到 B 容量 100、C 容量 50。

A:∞
B:100
C:50
已確定數
1

Reference solution

回報程式錯誤

完整程式

#include <iostream>
#include <vector>
#include <map>
#include <string>
#include <algorithm>
using namespace std;
int main() {
    int n, r, cs = 0;
    while (cin >> n >> r && (n || r)) {
        vector<vector<int>> w(n, vector<int>(n));
        map<string, int> id;
        auto get = [&](string s) {
            if (!id.count(s)) {
                int k = id.size();
                id[s] = k;
            }
            return id[s];
        };
        while (r--) {
            string a, b;
            int c;
            cin >> a >> b >> c;
            int u = get(a), v = get(b);
            w[u][v] = w[v][u] = max(w[u][v], c);
        }
        string a, b;
        cin >> a >> b;
        int start = get(a), goal = get(b);
        vector<int> best(n), used(n);
        best[start] = 1000000000;
        for (int step = 0; step < n; ++step) {
            int u = -1;
            for (int i = 0; i < n; ++i)
                if (!used[i] && (u < 0 || best[i] > best[u]))
                    u = i;
            if (u < 0)
                break;
            used[u] = 1;
            for (int v = 0; v < n; ++v)
                best[v] = max(best[v], min(best[u], w[u][v]));
        }
        cout << "Scenario #" << ++cs << '\n' << best[goal] << " tons\n\n";
    }
}

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

更多