You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

45 lines
963 B

#include <bits/stdc++.h>
using namespace std;
const int N = 110, M = 210;
int n, m, fa[N];
//结构体
struct Edge {
int a, b, w;
bool operator<(const Edge &t) {
return w < t.w;
}
} e[M];
//并查集
int find(int x) {
if (fa[x] != x) fa[x] = find(fa[x]); //路径压缩
return fa[x];
}
int main() {
cin >> n >> m;
//并查集初始化
for (int i = 1; i <= n; i++) fa[i] = i;
// Kruskal算法直接记录结构体
for (int i = 0; i < m; i++) {
int a, b, c;
cin >> a >> b >> c;
e[i] = {a, b, c};
}
sort(e, e + m); //不要忘记e数组的长度是边的数量
int res = 0;
//枚举每条边
for (int i = 0; i < m; i++) {
int a = find(e[i].a), b = find(e[i].b), c = e[i].w;
if (a != b)
fa[a] = b;
else
res += c; //去掉的边权
}
printf("%d\n", res);
return 0;
}