代码(Kruskal算法):
#include<bits/stdc++.h>
using namespace std;
struct rec{
int x;
int y;
int z;
}edge[200005];
int n,m,ans,tot=0;
int fa[5005];
bool cmp(rec a,rec b){
return a.z<b.z;
}
int get(int x){
if(fa[x]==x) return x;
else return fa[x]=get(fa[x]);
}
int main(){
scanf("%d%d",&n,&m);
for(int i=1;i<=m;i++)
scanf("%d%d%d",&edge[i].x,&edge[i].y,&edge[i].z);
sort(edge+1,edge+m+1,cmp);
for(int i=1;i<=n;i++) fa[i]=i;
for(int i=1;i<=m;i++){
int x=get(edge[i].x);
int y=get(edge[i].y);
if(x==y) continue;
fa[x]=y;
ans+=edge[i].z;
tot++;
}
if(tot<n-1){
cout<<"orz"<<endl;
return 0;
}
cout<<ans<<endl;
return 0;
}