上一篇恰好也是对图论的理解,所以这次解释比较比较少,如果有什么不太懂得地方,可以参考上面的,

也可以留言,我会尽最大努力解释:

View Code
# include<stdio.h>   
# include<stdlib.h>
# include<string.h>
# include<math.h>
struct node
{
int num1,num2; ///代表庄
int cost; ///代表庄之间的维修费用
};
node count[10000];
int flag[100];
int cmp(const void *a,const void *b)
{
struct node *c =(struct node *)a;
struct node *d =(struct node *)b;
if(c->cost!=d->cost)
return c->cost-d->cost;
else
return 1;
}
int find(int i)
{
if(flag[i]!=i)
return flag[i]=find(flag[i]);
return i;
}
void Merge(int x1,int y1)
{
int i,j;
i=find(x1);
j=find(y1);
if(i>j)
flag[i]=j;
else
flag[j]=i;
}
int main()
{
int i,j,n,m,k,d,k1,k2,sum;
char ch1,ch2;
while(scanf("%d",&n),n)
{
k=0;
for(i=0;i<n-1;i++)
{
getchar();
scanf("%c %d",&ch1,&m); ///稍加处理A代表庄一,B代表庄二……
{
for(j=0;j<m;j++)
{
getchar();
scanf("%c %d",&ch2,&d);
count[k].num1=ch1-'A'+1;
count[k].num2=ch2-'A'+1;
count[k].cost=d;
k++;
}
}
}
for(i=1;i<30;i++)
flag[i]=i;
qsort(count,k,sizeof(count[0]),cmp);
sum=0;
for(i=0;i<k;i++)
{
k1=find(count[i].num1);
k2=find(count[i].num2);
if(k1!=k2)
{
sum=sum+count[i].cost;
Merge(count[i].num1,count[i].num2);
}
}
printf("%d\n",sum);
}
return 0;
}

  

posted on 2011-08-09 14:28  world_ding  阅读(280)  评论(0编辑  收藏  举报