Author: lllyouo
Date: 20250224
tag: 最小生成树
link: https://www.acwing.com/problem/content/1145/问题描述
分析
参考代码
cpp
#include <bits/stdc++.h>
using namespace std;
const int N = 2010, M = 10010;
struct Edge {
int a, b, c;
bool operator < (const Edge& t) const {
return c < t.c;
}
} e[M];
int n, m, p[N];
int find(int x) {
if (p[x] != x) p[x] = find(p[x]);
return p[x];
}
int main() {
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 t, a, b, c; cin >> t >> a >> b >> c;
if (t == 1) {
p[find(a)] = find(b);
res += c;
} else e[k++] = {a, b, c};
}
sort(e, e + k);
for (int i = 0; i < k; i++) {
int pa = find(e[i].a), pb = find(e[i].b), c = e[i].c;
if (pa != pb) {
p[pa] = pb;
res += c;
}
}
cout << res << endl;
return 0;
}