这是Krukal算法
#include <stdio.h>
#include <stdlib.h>
struct road{
struct road *father;
int rank;
}Villages[27];
int main(){
void Sort(int road[][351], int n);
void Make_Set(struct road *p);
void Union(struct road *p1, struct road *p2);
struct road *Find_Set(struct road *p);
int i,j;
int boot,k;
char ch0,ch1;
int n,road[3][351],sum,weight;
struct road *p,*p1,*p2;
p=Villages;
while(scanf("%d",&n)&&n!=0)
{
boot=0;
sum=0;
boot=0;
for(i=0;i<n-1;i++)
{
scanf(" %c %d",&ch0,&k);
for(j=0;j<k;j++)
{
scanf(" %c %d",&ch1,&weight);
road[0][boot]=ch0-'A';
road[1][boot]=ch1-'A';
road[2][boot]=weight;
boot++;
}
}
for(i=0;i<n;i++)
Make_Set(p+i);
Sort(road,boot);
for(i=0;i<boot;i++)
{
if((p1=Find_Set(p+road[0][i]))!=(p2=Find_Set(p+road[1][i])))
{
Union(p1,p2);
sum+=road[2][i];
}
}
printf("%d\n",sum);
}
system("pause");
return 0;
}
void Sort(int road[][351], int n)
{
int i,j;
int temp,min,boot;
for(i=0;i<n-1;i++)
{
min=road[2][i];
boot=i;
for(j=i+1;j<n;j++)
{
if(min>road[2][j])
{
min=road[2][j];
boot=j;
}
}
if(boot!=i)
{
road[2][boot]=road[2][i];
road[2][i]=min;
min=road[1][boot];
road[1][boot]=road[1][i];
road[1][i]=min;
min=road[0][boot];
road[0][boot]=road[0][i];
road[0][i]=min;
}
}
}
void Make_Set(struct road *p)
{
p->father=p;
p->rank=1;
}
void Union(struct road *p1, struct road *p2)
{
if(p1->rank>p2->rank)
{
p2->father=p1;
}
else
{
p1->father=p2;
if(p1->rank==p2->rank)
p2->rank++;
}
}
struct road *Find_Set(struct road *p)
{
struct road *r,*q;
r=p;
while(r!=r->father)
r=r->father;
while(p!=r)
{
q=p;
p=p->father;
q->father=r;
}
return r;
}