空间复杂度:O(N+E)
时间复杂度:O(ElogE)
#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
const int maxn=5e3+5, maxm=2e5+5;
int f[maxn], n, m; //f为并查集数组
struct Edge{ int x, y, key; }edge[maxm];
inline bool cmp(Edge a, Edge b){ return a.key < b.key; }
inline int find(int x) //并查集的路径压缩
{
if(f[x]==x) return x;
else return f[x]=find(f[x]);
}
//inline int find(int x) { return f[x]==x ? x : f[x]=find(f[x]); }
int kruskal()
{
sort(edge+1, edge+m+1, cmp); //边排序
for(int i=1; i<=n; i++) f[i] = i; //每个点初始化为独立集合
int cnt=0, ans=0; //ans统计加入的边数,满足mst时等于n-1
for(int i=1; i<=m && cnt!=n-1; i++)
{
int x=edge[i].x, y=edge[i].y, key=edge[i].key;
if(find(x)!=find(y))
ans+=key, cnt++, f[find(x)] = find(y);
}
return cnt==n-1 ? ans : -1;
}
int main(void)
{
scanf("%d%d", &n, &m);
for(int i=1; i<=m; i++) scanf("%d%d%d", &edge[i].x, &edge[i].y, &edge[i].key);
int ans=kruskal();
if(ans==-1) printf("orz
");
else printf("%d
", ans);
return 0;
}