Files
HuangHai 1f397eca87 'commit'
2025-08-30 18:35:01 +08:00

58 lines
1.3 KiB
C++
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

#include <bits/stdc++.h>
using namespace std;
const int INF = 0x3f3f3f3f;
const int N = 110;
int b[N];
int n, m;
int g[N][N]; // 稠密图,邻接矩阵
int dis[N]; // 这个点到集合的距离
bool st[N]; // 是不是已经使用过
int res; // 最小生成树里面边的长度之和
int sum; // 总边长
// 普利姆算法求最小生成树
int prim(int s) {
// 由于调用多次prim,所以每次需要清零
memset(dis, 0x3f, sizeof dis);
dis[s] = 0;
res = 0;
// 标识
b[s] = 1;
for (int i = 0; i < n; i++) { // 迭代n次
int t = -1;
for (int j = 1; j <= n; j++)
if (!st[j] && (t == -1 || dis[t] > dis[j])) t = j;
// if (i && dis[t] == INF) return INF; // 非连通图,没有最小生成树
if (i && dis[t] != INF) res += dis[t], b[t] = 1;
for (int j = 1; j <= n; j++)
if (!st[j] && g[t][j] < dis[j]) dis[j] = g[t][j];
st[t] = true;
}
return res;
}
int main() {
cin >> n >> m;
memset(g, 0x3f, sizeof g);
while (m--) {
int a, b, c;
cin >> a >> b >> c;
g[a][b] = g[b][a] = c;
sum += c; // 总边长
}
int s = 0;
for (int i = 1; i <= n; i++)
if (!b[i]) s += prim(i);
printf("%d\n", sum - s);
return 0;
}