#include<iostream>
#include<string.h>
#include<algorithm>
using namespace std;
int parent[105],n,m;struct hyf {
int x,y,len;
} p[105];bool cmp( hyf a,hyf b) {
return a.len<b.len;
}// 将村庄间的路进行排序int find(int x) {
if(x!=parent[x])
parent[x]=find(parent[x]);
return parent[x];
}//找根节点 就是判断是否在同一个集合void fun(int x,int y) {
int tx,ty;
tx=find(x);
ty=find(y);
if(tx!=ty)
parent[tx]=ty;
}//将节点合并 就是将不同集合的元素合并在一个集合// 道路条数n 村庄m
int main() {
int i,j,tx,ty,tz;
while(cin>>n>>m) {
for(i=1; i<=m; i++)
parent[i]=i;//初始将每一个村庄看成一个集合
for(i=0; i<n; i++) {
cin>>p[i].x>>p[i].y>>p[i].len;
}
sort(p,p+n,cmp);
int ans=0;
for(i=0; i<n; i++) {//重点
if(m>1) {
tx=p[i].x;
ty=p[i].y;
tz=p[i].len;
if(find(tx)==find(ty))
continue;
else {
fun(tx,ty);
m--;
ans+=tz;
}
}
}
if(m==1)
printf("%d\n",ans);
else cout<<"不能连通"<<endl;}
}
数据输入
8 6
1 3 10
1 5 30
1 6 100
2 3 5
3 4 50
4 6 10
5 4 20
5 6 60
输出为75
图见数据结构171 图6.22