a273中等最大瓶頸生成樹・降序 Kruskal

TOI 2022/10 潛力組:資料中心

最大化保留樹中最小的邊,而不是求所有邊容量總和。

前往題目練習 →回報教學錯誤時間 O(M log M + M α(N))、空間 O(N+M);容量 ≤ 10⁹,無須把容量總和當成答案。

解題思路

任意兩點恰有一條路徑,表示保留圖必須是一棵生成樹。樹中每條邊的兩端本身也是一對中心,所以所有點對的最差路徑瓶頸,恰好等於整棵樹最小的邊容量。問題因此化為最大化生成樹的最小邊。

把邊按容量由大到小加入 DSU,只有不同分量的邊才保留。當成功合併到 N−1 條時,最後一條的容量 f 就是答案。容量嚴格大於 f 的所有邊尚不足以連通全圖,任何生成樹都必須用到不大於 f 的邊;目前構造已達此上界。

Step-by-step animation

範例容量 9、8、7、2

回報動畫錯誤
步驟 1 / 3

加入 2—3

最大容量 9,先合併兩個單點分量。

{1}
{2,3}
{4}
已選邊
1
目前瓶頸
9

Reference solution

回報程式錯誤

完整程式

#include <iostream>
#include <vector>
#include <algorithm>
#include <numeric>
using namespace std;
struct Edge {
    int a, b, w;
};
int main() {
    int n, m;
    cin >> n >> m;
    vector<Edge> e(m);
    for (auto &x : e)
        cin >> x.a >> x.b >> x.w;
    sort(e.begin(), e.end(), [](const Edge &a, const Edge &b) { return a.w > b.w; });
    vector<int> p(n + 1), size(n + 1, 1);
    iota(p.begin(), p.end(), 0);
    auto find = [&](int x) {
        while (x != p[x]) {
            p[x] = p[p[x]];
            x = p[x];
        }
        return x;
    };
    int count = 0;
    for (auto x : e) {
        int a = find(x.a), b = find(x.b);
        if (a == b)
            continue;
        if (size[a] < size[b])
            swap(a, b);
        p[b] = a;
        size[a] += size[b];
        if (++count == n - 1) {
            cout << x.w << '\n';
            break;
        }
    }
}

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

更多