题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=1863
源代码:
#include<iostream>
#include<cstdlib>
#include<cstdio>
#include<algorithm>
using namespace std;
#define N 100
typedef struct Edge
{
int c1,c2,value;
}edge;
edge e[N*N];
int node[N];
bool comp(const edge &a,const edge &b)
{
return a.value<b.value?1:0;
}
int find_set(int n)
{
if(node[n]==-1)return n;
else return node[n]=find_set(node[n]);
}
bool Merge(int s1,int s2)
{
int r1=find_set(s1);
int r2=find_set(s2);
if(r1==r2)return 0;
if(r1<r2)node[r2]=r1;
else node[r1]=r2;
return 1;
}
int main()
{
int n,m,i;
while(scanf("%d%d",&n,&m)!=EOF&&n)
{
int count=0,sum=0;
memset(node,-1,sizeof(node));
for(i=0;i<n;i++)
{
scanf("%d%d%d",&e[i].c1,&e[i].c2,&e[i].value);
}
sort(e,e+n,comp);
for(i=0;i<n;i++)
{
if(Merge(e[i].c1-1,e[i].c2-1))
{
count++;
sum+=e[i].value;
}
if(count==m-1)break;
}
if(count!=m-1)printf("?\n");
else printf("%d\n",sum);
}
return 0;
}