最小生成树的题目,用到查并集,本题要求出连接所有点的最短路径。
首先,对于每条边用结构体存储,记录两个顶点和两点间的距离;
然后就是最小生成树的核心思想:每一次选取最小的那条边,如果该边的两个点尚未连通(两个点不在一个集合),那么就连接两个点,否则,不用这条边;
每次连接两个顶点时,将它们的所在子树的树根相连,减少树的层数。
呵呵,在这里是第一次使用qsort排序~
#include<stdio.h>
#include<stdlib.h>
struct road //用结构体储存每一条边
{
int x;
int y;
int len;
}a[10000];
int cmp(const void *a,const void *b)
{
return (*(struct road*)a).len-(*(struct road*)b).len;
}
int find(int x,int *father)
{
if(father[x]==x)
return x;
else
return find(father[x],father);
}
int main()
{
int p,r,i,A,B,count,father[51];
while(scanf("%d",&p),p!=0)
{
for(i=1;i<=p;i++) //按序号编号,大多数情况下,father[0]是不用的!!
father[i]=i;
scanf("%d",&r);
for(i=0;i<r;i++)
scanf("%d%d%d",&a[i].x,&a[i].y,&a[i].len);
qsort(a,r,sizeof(a[0]),cmp); //按边由小到大排序,这样可以保证每次都取到最小的边
for(i=0,count=0;i<r;i++)
{
A=find(a[i].x,father);
B=find(a[i].y,father);
if(A!=B)
{
father[A]=B;
count+=a[i].len;
}
}
printf("%d\n",count);
}
return 0;
}