解題思路
在原題通常採用的簡單道路圖模型中,沒有攝影機的道路不能留下任何環,否則賽車可完全沿該環避開攝影機。故這些道路必須形成森林。總安裝成本等於所有道路成本總和減去未安裝道路的成本,因此要最大化保留森林的權重。正成本且原圖連通,最優森林能擴充為生成樹。
將邊依成本由大到小排序,使用並查集。若兩端尚未連通就保留該邊並合併;否則加入會形成環,必須在此邊安裝攝影機並累加成本。最大生成樹的交換性質保證保留較昂貴的可行邊不會損失最佳解。依開頭的組數處理資料,最後的 0 不再讀成新案例。
Step-by-step animation
示意:三角形成本 7、5、2
步驟 1 / 3
保留 7
先連接 1、2。
1−2:7
2−3:5
1−3:2
- 安裝
- 0
#include <iostream>
#include <vector>
#include <algorithm>
#include <numeric>
using namespace std;
struct Edge {
int u, v, w;
};
struct DSU {
vector<int> p, size;
DSU(int n) : p(n), size(n, 1) {
iota(p.begin(), p.end(), 0);
}
int find(int x) {
return p[x] == x ? x : p[x] = find(p[x]);
}
bool join(int a, int b) {
a = find(a);
b = find(b);
if (a == b)
return false;
if (size[a] < size[b])
swap(a, b);
p[b] = a;
size[a] += size[b];
return true;
}
};
int main() {
int tests;
cin >> tests;
while (tests--) {
int n, m;
cin >> n >> m;
vector<Edge> e(m);
for (auto &x : e) {
cin >> x.u >> x.v >> x.w;
--x.u;
--x.v;
}
sort(e.begin(), e.end(), [](Edge a, Edge b) { return a.w > b.w; });
DSU d(n);
long long answer = 0;
for (auto x : e)
if (!d.join(x.u, x.v))
answer += x.w;
cout << answer << '\n';
}
}先試著自己完成,再切換語言比對解法。參考程式可複製到題目編輯器。