最小生成树 : 拆点
https://www.acwing.com/problem/content/1145/
思路
- \(把已有的边加上,会形成各个连通块,等价于把每个连通块当成一个点去做Kruskal算法.\)
#include <bits/stdc++.h>
using namespace std;
#define IO ios::sync_with_stdio(false);cin.tie(0); cout.tie(0)
inline int lowbit(int x) { return x & (-x); }
#define ll long long
#define pb push_back
#define PII pair<int, int>
#define x first
#define y second
#define inf 0x3f3f3f3f
const int N = 2010, M = 10010;
int n, m;
int p[N];
struct Edge {
int a, b, w;
bool operator< (const Edge &t) const {
return w < t.w;
}
}e[M];
int find(int x) {
if (p[x] != x) p[x] = find(p[x]);
return p[x];
}
int main() {
IO;
cin >> n >> m;
for (int i = 1; i <= n; ++i) p[i] = i;
int res = 0, k = 0;
for (int i = 0; i < m; ++i) {
int a, b, w, t;
cin >> t >> a >> b >> w;
if (t == 1) {
res += w;
p[find(a)] = find(b);
} else e[k++] = {a, b, w};
}
sort(e, e + k);
for (int i = 0; i < k; ++i) { // kruskal
int a = find(e[i].a), b = find(e[i].b), w = e[i].w;
if (a != b) {
p[a] = b;
res += w;
}
}
cout << res << '\n';
return 0;
}