\(kruskal\),有兴趣\(heap\_prim\)。
#include <bits/stdc++.h>
using namespace std;
struct tEdge {
int a, b, c;
bool operator < (const tEdge &y) const {
return c < y.c;
}
};
tEdge edge[100005];
int fa[1005];
int father(int x) {return (fa[x] == x) ? x : (fa[x] = father(fa[x]));}
bool combine(int x, int y) {
int fx = father(x), fy = father(y);
if (fx != fy) {fa[fx] = fy; return true;}
return false;
}
int main() {
int n, m;
scanf("%d%d", &n, &m);
for (int i = 0; i < m; ++i) scanf("%d%d%d", &edge[i].a, &edge[i].b, &edge[i].c);
sort(edge, edge + m);
for (int i = 1; i <= n; ++i) fa[i] = i;
int ans = 0;
for (int i = 0, k = 0; k < n - 1; ++i)
if (combine(edge[i].a, edge[i].b) == true) {++k; ans += edge[i].c;}
printf("%d", ans);
return 0;
}