kruskal算须乱为余充酒法实现 c代码
的有关信息介绍如下:#include<s块果头tdio.h>
#include<stdlib.h>
#d等氢未互织efineMAX100
/*定义边(x,y),权为w*/
typedefstruct
{
intx,y;
intw;
}edg绿左司景孩丰伤制但年米e;
edgee[MAX];
/*rank[x]表示x的秩*/
intrank[MAX];
/*f资粮唱味ather[x]表示x的父节点*/
intfather[MAX];
intsum;
/*比较函数,按权值(相同则按x坐标船才)非降序排序*/
intcmp(constvoid*a,constvoid*b)
{
if((*(edge*)至易医互布善呢紧广老a).w==(*(edge*)b).w)
{
return(*(edge*)a).x-(*德坏者满后固河宣施展事(edge*)b).x;
}
r360问答eturn(*(ed顾论念例ge*)a).w-(*(edge*)b).w;
}
/装两*初始化集合*/
voidMake_Set(intx)
{
father[x]=x;
rank[x]=0;
}
/*查找x元素所在的集合,回溯时压缩路径*/
intFind_Set浓报(intx)
{
if(x!=father[x])
{
father[x走升游守信指顺德]=Find_Set(father[x]);
}
returnfather[x];
}
/*合并x,y持所在的集合*/
voidUnion(intx,inty,intw)
{
if(x==y)return;
/*将秩较小的树连接到秩较大的树后脚故操西怎弦婷*/
if(rank[x]>rank[y])
{
father[y反]=x;
}
else
{
if(rank[x]=边逐他空做=rank[y])
{
rank[y]++;
}
father[x]=y;
}
sum+=w;
}
/*主函数*/
intmain()
环移练请道{
inti,n;
intx,y;
charchx,chy;
/*读取边的数目*/
scanf("%d",&n);
getchar();
/*读取边信息并初始化集合*/
for(i=0;i<n;i++)
{
scanf("%c%c%d",&chx,&chy,&e[i].w);
getchar();
e[i].x=chx-'A';
e[i].y=chy-'A';
Make_Set(i);
}
/*将边排序*/
qsort(e,n,sizeof(edge),cmp);
sum=0;
for(i=0;i<n;i++)
{
x=Find_Set(e[i].x);
y=Find_Set(e[i].y);
if(x!=y)
{
printf("%c-%c:%d\n",e[i].x+'A',e[i].y+'A',e[i].w);
Union(x,y,e[i].w);
}
}
printf("Total:%d\n",sum);
//system("pause");
return0;
}