a722中等Floyd–Warshall 與網路直徑

CPE:Degrees of Separation (UVa 1056)

求所有人之間最短距離,再判斷連通性。

前往題目練習 →回報教學錯誤時間 O(P³),空間 O(P²),P≤50。

解題思路

姓名映射為整數編號,建立 P×P 距離矩陣,對角線為 0、已知關係為雙向的 1,其餘為無限大。即使某些人從未出現在關係中,仍須保留 P 個節點,否則會漏掉孤立者。

依序允許第 k 人成為中繼點,更新 d[i][j]=min(d[i][j],d[i][k]+d[k][j])。k 的外層迴圈保證每階段只使用已允許的中繼點。完成後有無限距離即 DISCONNECTED,否則最大值為直徑。讀到 0 0 停止,每筆 Network k 後印空行。

Step-by-step animation

示意:A–B–C,P=3

回報動畫錯誤
步驟 1 / 3

建立邊

A 到 C 暫時未知。

A–B=1
B–C=1
A–C=∞
P
3

Reference solution

回報程式錯誤

完整程式

#include <iostream>
#include <vector>
#include <map>
#include <string>
#include <algorithm>
using namespace std;
int main() {
    int p, r, cs = 0;
    while (cin >> p >> r && (p || r)) {
        vector<vector<int>> d(p, vector<int>(p, 1000000));
        for (int i = 0; i < p; ++i)
            d[i][i] = 0;
        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;
            cin >> a >> b;
            int u = get(a), v = get(b);
            d[u][v] = d[v][u] = 1;
        }
        for (int k = 0; k < p; ++k)
            for (int i = 0; i < p; ++i)
                for (int j = 0; j < p; ++j)
                    d[i][j] = min(d[i][j], d[i][k] + d[k][j]);
        int best = 0;
        for (auto &row : d)
            for (int x : row)
                best = max(best, x);
        cout << "Network " << ++cs << ": ";
        if (best >= 1000000)
            cout << "DISCONNECTED";
        else
            cout << best;
        cout << "\n\n";
    }
}

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

更多