时间复杂度: E为图中的边数
算法思想:从权值最小的边开始,如果这条边连接的两个节点于图G中不在同一个连通分量中,则添加这条边到图G中
#include<iostream>
#include<algorithm>
#include<cstdio>
using namespace std;
const int maxe = 4000;
const int maxn = 55;
struct Edge
{
int u, v, w;
}edge[maxe];
bool cmp(Edge p, Edge q)
{
return p.w < q.w;
}
int fa[maxn];
int find_ancestor(int x)
{
return fa[x] == x ? x : fa[x] = find_ancestor(fa[x]);
}
int main()
{
int n, m, ans, tol;
while(cin >> n)
{
cin >> m;
tol = 0;
for(int i = 0; i <= n; i++)
fa[i] = i;
for(int i = 0; i < m; i++)
{
int u, v, w;
scanf("%d%d%d", &u, &v, &w);
edge[tol].u = u;
edge[tol].v = v;
edge[tol++].w = w;
}
sort(edge, edge+tol, cmp);
ans = 0;
for(int i = 0; i < tol; i++)
{
int x = find_ancestor(edge[i].u);
int y = find_ancestor(edge[i].v);
if(x != y)
{
ans += edge[i].w;
fa[y] = x;
}
}
printf("%d\n", ans);
}
return 0;
}