#include <iostream>
#include <stdio.h>
#include <bits/stdc++.h>
using namespace std;
struct edge{
int from,to,cost;
};
int v,e;
edge E[100];
int fa[100];
bool cmp(edge a,edge b){
return a.cost<b.cost;
}
void init(){
for(int i=0;i<v;i++) fa[i]=i;
}
int find(int a){
if(fa[a]==a) return a;
else return fa[a]=find(fa[a]);
}
void unit(int a,int b){
a=find(a);
b=find(b);
if(a==b) return;
fa[a]=b;
}
bool same(int a,int b){
return find(a)==find(b);
}
int kruskal(){
int len=0;
init();
sort(E,E+e,cmp);
for(int i=0;i<e;i++){
edge ee=E[i];
if(!same(ee.from,ee.to)){
unit(ee.from,ee.to);
len+=ee.cost;
}
}
return len;
}
int main(){
cin>>v>>e;
for(int i=0;i<e;i++){
int s,t,c;
cin>>s>>t>>c;
E[i].from=s;
E[i].to=t;
E[i].cost=c;
}
cout<<kruskal();
return 0;
}
/*
7 10
0 1 2
0 2 5
1 2 4
1 3 6
2 3 2
1 4 10
3 5 1
4 5 3
4 6 5
5 6 9
*/
kruscal最小生成树
最新推荐文章于 2021-03-14 22:56:43 发布