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.

70 lines
1.8 KiB

2 years ago
#include <bits/stdc++.h>
using namespace std;
const int N = 110, M = 210;
2 years ago
const int INF = 0x3f3f3f3f;
2 years ago
2 years ago
int n, m; // n条顶点,m条边
int res; // 最小生成树的权值和
int cnt; // 最小生成树的结点数
// Kruskal用到的结构体
struct Node {
int a, b, c;
bool const operator<(const Node &t) const {
return c < t.c; // 边权小的在前
2 years ago
}
2 years ago
} edge[M]; // 数组长度为是边数
2 years ago
2 years ago
// 并查集
int p[N];
2 years ago
int find(int x) {
2 years ago
if (p[x] != x) p[x] = find(p[x]);
return p[x];
}
// Kruskal算法
2 years ago
void kruskal() {
2 years ago
// 1、按边权由小到大排序
sort(edge, edge + m);
// 2、并查集初始化
for (int i = 1; i <= n; i++) p[i] = i;
// 3、迭代m次
for (int i = 0; i < m; i++) {
int a = edge[i].a, b = edge[i].b, c = edge[i].c;
a = find(a), b = find(b);
if (a != b)
p[a] = b, res += c, cnt++; // cnt是指已经连接上边的数量
}
2 years ago
// 这句话需要注释掉,原因如下:
/*
6 6
1 2 5
1 3 4
2 3 8
4 5 7
4 6 2
5 6 1
1,2,34,5,6
*/
2 years ago
// 4、特判是不是不连通
2 years ago
// if (cnt < n - 1) res = INF;
2 years ago
}
2 years ago
2 years ago
int main() {
cin >> n >> m;
2 years ago
int sum = 0;
2 years ago
// Kruskal算法直接记录结构体
for (int i = 0; i < m; i++) {
int a, b, c;
cin >> a >> b >> c;
2 years ago
edge[i] = {a, b, c};
sum += c;
2 years ago
}
2 years ago
kruskal();
printf("%d\n", sum - res);
2 years ago
return 0;
}