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.

58 lines
1.3 KiB

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

#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;
}