Description
省政府“畅通工程”的目标是使全省任何两个村庄间都可以实现公路交通(但不一定有直接的公路相连,只要能间接通过公路可达即可)。经过调查评估,得到的统计表中列出了有可能建设公路的若干条道路的成本。现请你编写程序,计算出全省畅通需要的最低成本。
Input
测试输入包含若干测试用例。每个测试用例的第1行给出评估的道路条数 N、村庄数目M ( < 100 );随后的 N
行对应村庄间道路的成本,每行给出一对正整数,分别是两个村庄的编号,以及此两村庄间道路的成本(也是正整数)。为简单起见,村庄从1到M编号。当N为0时,全部输入结束,相应的结果不要输出。
Output
对每个测试用例,在1行里输出全省畅通需要的最低成本。若统计数据不足以保证畅通,则输出“?”。
Sample Input
3 3
1 2 1
1 3 2
2 3 4
1 3
2 3 2
0 100
Sample Output
3
?
/* 克鲁斯卡尔算法 */
/*满足的条件是:
用一个结构体存下每一条遍 的值和两个节点,对遍从小到大排序,
然后依次判断两个点是否在一个集合了,如果在就不执行操作,
如果不在就执行操作,执行N-1就完成了一棵最小生成树
m 个点 连接 m-1 条边即可
*/
#include<stdio.h>
#include<string.h>
#include<algorithm>
#include<iostream>
using namespace std;
int F[1001];
struct TREE
{
int b;
int e;
int p;
} t[1001];
bool cmp(struct TREE x,struct TREE y)
{
return x.p<y.p;
}
int find(int x)
{
if(x!=F[x])
F[x]=find(F[x]);
return F[x];
}
void U(int x,int y)
{
int root1,root2;
root1=find(x);
root2=find(y);
if(root1!=root2)
F[root2]=root1;
}
int main()
{
int n,m,i,j,ans=0,num=0;
int root1,root2;
while(scanf("%d %d",&n,&m)&&n!=0)
{
num=0;
ans=0;
for(i=1; i<=m; i++)
{
F[i]=i;
}
for(i=0; i<n; i++)
scanf("%d %d %d",&t[i].b,&t[i].e,&t[i].p);
sort(t,t+n,cmp);
for(i=0; i<n; i++)
{
root1=find(t[i].b);
root2=find(t[i].e);
if(root1!=root2)
{
ans+=t[i].p;
U(t[i].b,t[i].e);
num++;
}
}
if(num==m-1)
printf("%d\n",ans);
else
printf("?\n");
}
}