http://acm.hdu.edu.cn/showproblem.php?pid=1863
#include <stdio.h>
#include <algorithm>
using namespace std;
struct Edge
{
int a,b;
int cost;
}edge[5000];
int Tree[100];
bool cmp(Edge A,Edge B)
{
return A.cost<B.cost;
}
int findRoot(int x)
{
if (Tree[x]==-1)
{
return x;
}
else
{
int tmp=findRoot(Tree[x]);
Tree[x]=tmp;
return tmp;
}
}
int main()
{
int n,m,a,b,i;
while (scanf("%d%d",&n,&m)!=EOF && n!=0)
{
for(i=1;i<=n;i++)
{
scanf("%d%d%d",&edge[i].a,&edge[i].b,&edge[i].cost);
}
sort(edge+1,edge+1+n,cmp);
for (i=1;i<=m;i++)
{
Tree[i]=-1;
}
int ans=0,tag=0;
for (i=1;i<=n;i++)
{
a=findRoot(edge[i].a);
b=findRoot(edge[i].b);
if (a!=b)
{
Tree[a]=b;
ans+=edge[i].cost;
}
}
for (i=1;i<=m;i++) //多了一个判定,是否是连通图
{
if (Tree[i]==-1)
{
tag++;
}
}
if (tag>1) //连通分量>1,所以不是连通图,道路数据不足
{
printf("?\n");
}
else
{
printf("%d\n",ans);
}
}
return 0;
}