a307困難糧食來源預先合併的 Kruskal 最小生成樹
TOI 2023/05 潛力組:糧食便道
將多源供應需求轉成零成本超級節點連通,避免強迫糧食城鎮彼此修路。
解題思路
想像增加一個超級節點,以免費道路連到每個生產糧食的城鎮。原圖的合法方案等價於新增圖中把所有點連通:每個城鎮透過某個糧食城鎮到超級節點即可。反向看,移除這些免費邊後,每個道路連通塊仍至少含一個糧食來源,符合原題,而且真實便道總成本不變。
因此先用並查集合併所有糧食城鎮,再將候選道路按成本遞增,只有兩端目前屬不同集合才興建並合併。這就是先選完所有免費邊的 Kruskal;切割性質保證每次選取跨集合的最低成本邊可以包含在某棵最小生成樹中。生產城鎮之間的道路可能被直接略過,因為它們在模型中已免費相連。題目保證可行,不需額外輸出無解。
Step-by-step animation
公開範例:糧食城鎮為 1、4
步驟 1 / 3
免費合併來源
先將 1、4 視為同一集合;成本 1 的 1–4 邊不必興建。
{1,4}
{2}
{3}
- 已付成本
- 0
- 來源
- 1、4
#include <algorithm>
#include <array>
#include <iostream>
#include <numeric>
#include <vector>
using namespace std;
struct DSU {
vector<int> p, sz;
DSU(int n) : p(n + 1), sz(n + 1, 1) {
iota(p.begin(), p.end(), 0);
}
int find(int x) {
while (x != p[x]) {
p[x] = p[p[x]];
x = p[x];
}
return x;
}
bool unite(int a, int b) {
a = find(a);
b = find(b);
if (a == b)
return false;
if (sz[a] < sz[b])
swap(a, b);
p[b] = a;
sz[a] += sz[b];
return true;
}
};
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
int n, m, k;
cin >> n >> m >> k;
DSU d(n);
int root;
cin >> root;
for (int i = 1; i < k; i++) {
int x;
cin >> x;
d.unite(root, x);
}
vector<array<int, 3>> edges(m);
for (auto &e : edges)
cin >> e[1] >> e[2] >> e[0];
sort(edges.begin(), edges.end());
long long ans = 0;
for (auto [cost, a, b] : edges)
if (d.unite(a, b))
ans += cost;
cout << ans << '\n';
}先試著自己完成,再切換語言比對解法。參考程式可複製到題目編輯器。