Problem Description
漳州市政府调查乡村交通状况,得到的统计表中列出了任意两村庄间的距离。市政府的目标是使全省任何两个村庄间都可以实现公路交通(但不一定有直接的公路相连,只要能间接通过公路可达即可),并要求铺设的公路总长度为最小。请计算最小的公路总长度。
Input
测试输入包含若干测试用例。每个测试用例的第1行给出村庄数目N(N<100)和M;随后的M行对应村庄间的距离,每行给出一对正整数,分别是两个村庄的编号,以及此两村庄间的距离。为简单起见,村庄从1到N编号。
当N、M为0时,输入结束,该用例不被处理。
Output
对每个测试用例,在1行里输出最小的公路总长度,如果未能找到请输出"no found!"。
Sample Input
3 3
1 2 1
1 3 2
2 3 4
4 6
1 2 1
1 3 4
1 4 1
2 3 3
2 4 2
3 4 5
0 0
Sample Output
3
5
#include<iostream>
using namespace std;
struct Node{int i,j,w;};
int n,e,parent[101];
Node edge[101];
int FindRoot(int v)
{
int t=v;
while(parent[t]>-1)
t=parent[t];
return t;
}
void Kruskal()
{
int i,j,k,min,vex1,vex2;
for(i=1;i<=n;i++)
parent[i]=-1;
int cost=0;
for(j=1;j<=n-1;j++)
{
min=99999;i=-1;
for(k=0;k<e;k++)
{
if(edge[k].w<min)
{
min=edge[k].w;i=k;
}
}
if(min!=99999)
{
vex1=FindRoot(edge[i].i);
vex2=FindRoot(edge[i].j);
if(vex1!=vex2)
{
cost+=min;
parent[vex2]=vex1;
/*cout<<"("<<edge[i].i<<","<<
edge[i].j<<")"<<min<<endl;*/
edge[i].w=99999;
}
else {edge[i].w=99999;j--;}
//for(int h=1;h<=n;h++)
//cout<<parent[h]<<" ";cout<<endl;
}
else break;
}
if(j==n)cout<<cost<<endl;
else cout<<"no found!\n";
}
int main()
{
while(cin>>n>>e)
{
if(n==0 && e==0)break;
for(int k=0;k<e;k++)
{
cin>>edge[k].i>>edge[k].j>>edge[k].w;
}
Kruskal();
}
return 0;
}