题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=1863
思路:一个简单的最小生成树,用的并查集和kruskal算法来解;
代码:
#include<cstring>
#include<cstdio>
#include<algorithm>
using namespace std;
struct node
{
int fo,to,w;
bool operator <(const node &a)const
{
return w<a.w;
}
} E[1009];
int p[1009],n,m;
int cha(int x)
{
if(p[x]==-1)
return x;
return p[x]=cha(p[x]);
}
int kk()
{
int ans=0,cnt=0;
for(int i=0; i<m; i++)
{
int x=cha(E[i].fo);
int y=cha(E[i].to);
if(x!=y)
{
cnt++;
ans+=E[i].w;
p[x]=y;
}
}
if(cnt<n-1)return -1;
return ans;
}
int main()
{
while (scanf("%d",&m)!=-1)
{
scanf("%d",&n);
if(m==0)break;
memset(p,-1,sizeof(p));
for(int i=0;i<m;i++)
{
scanf("%d%d%d",&E[i].fo,&E[i].to,&E[i].w);
}
sort(E,E+m);
int nk=kk();
if(nk==-1)printf("?\n");
else printf("%d\n",nk);
}
}