克丽丝卡尔算法的主要思想是将两点之间的距离排序,。,,然后从小到大依此用并查集判断这条边是不是构成环,,若不是环就能就能用上。。。。
题目连接 http://acm.hdu.edu.cn/showproblem.php?pid=1879
#include<stdio.h>
#include<string.h>
#include<algorithm>
#define max 100000
int n,zx[101];
struct node
{
int a,b;
int len;
}st[5000];
bool cmp(struct node t1,struct node t2)
{
return t1.len <t2.len;
}
void in()
{
for(int i=1;i<=n;i++)
zx[i]=i;
}
int find(int a)
{
return zx[a]==a?zx[a]:zx[a]=find(zx[a]);
}
void hb(int a,int b)
{
int x=find(a);
int y=find(b);
if(x!=y)
zx[x]=y;
}
int kris()
{
int i,a,b,c,sum=0;
for(i=0;i<n*(n-1)/2;i++)
{
a=st[i].a;
b=st[i].b;
c=st[i].len;
if(find(a)!=find(b))
{
hb(a,b);
sum+=c;
}
}
return sum;
}
int main()
{
while(scanf("%d",&n)&&n)
{
int a,c,b,s;
in();
for(int i=0;i<n*(n-1)/2;i++)
{
scanf("%d%d%d",&a,&b,&c);
st[i].a=a;
st[i].b=b;
st[i].len=c;
}
std::sort(st,st+n*(n-1)/2,cmp);
s=kris();
printf("%d\n",s);
}
}