思路:Kruskal模板题
代码:
#include<iostream>
#include<stdio.h>
#include<string.h>
#include<vector>
#include<algorithm>
using namespace std;
#define LL long long int
const int MAXN=1e2+2;
struct edge{
int u,v,w;
}e[MAXN];
int pre[MAXN];
int n,k;
bool cmp(edge a,edge b){
return a.w<b.w;
}
void init(){
for(int i=1;i<=n;++i){
pre[i]=i;
}
}
int find(int x){
if(x!=pre[x])
pre[x]=find(pre[x]);
return pre[x];
}
bool join(int x,int y){
int fx=find(x),fy=find(y);
if(fx!=fy){
pre[fy]=fx;
return true;
}
return false;
}
int main(){
scanf("%d %d",&n,&k);
init();
for(int i=0;i<k;++i){
scanf("%d %d %d",&e[i].u,&e[i].v,&e[i].w);
}
sort(e,e+k,cmp);
int count=0,ans=0;
for(int i=0;i<k;++i){
if(join(e[i].u, e[i].v)){
++count;
ans+=e[i].w;
}
if(count==n-1)
break;
}
printf("%d\n",ans);
return 0;
}