#include <string.h>
#include <algorithm>
#include <iostream>
using namespace std;
int father[111];
struct node
{
int x,y,cost;
}map[111];
bool cmp(node a,node b)
{
return a.cost <= b.cost;
}
int find(int x)
{
int r=x;
while(father[r] != r)
{
r = father[r];
}
int i=x,k;
while(i != r)
{
k = father[r];
father[i] = r;
i = k;
}
return r;
}
int main()
{
int n,m,i,ans,sum;
while(~scanf("%d%d",&n,&m))
{
if(n == 0)
break;
ans = 0;
sum = 1;
for(i=0;i<n;i++)
scanf("%d%d%d",&map[i].x,&map[i].y,&map[i].cost);
sort(map,map+n,cmp);
memset(father,0,sizeof(father));
for(i=1;i<=m;i++)
father[i] = i;
for(i=0;i<n;i++)
{
int f1 = find(father[map[i].x]);
int f2 = find(father[map[i].y]);
if(f1 != f2)
{
father[f1] = f2;
ans+=map[i].cost;
sum++;
}
}
if(sum != m)
printf("?\n");
else
printf("%d\n",ans);
}
return 0;
}
HDU1863并查集和kruskal算法
最新推荐文章于 2018-09-10 09:03:19 发布