链接网址:http://poj.org/problem?id=1251
分析:题意第一行输入一个数字代表是n个村庄,接下来是n-1行,每行的第二数字是表示与该村相连的村子个数,即要修的路的条数,接下来的字母和数字表示修到村子和所需的费用。问你要连通所有的村子所需要的最少费用是多少。
#include<iostream>
#include<cstdio>
using namespace std;
const int N=100;
int n,t,ans,p[N];
struct node
{
int x,y,d;
}e[N];
void Init(int n)//打表
{
for(int i=0;i<n;i++)
p[i]=i;
}
int Find(int x)//找根结点
{
if(p[x]==x) return x;
else return p[x]=Find(p[x]);
}
void mrege(int x,int y)//合并两个结点
{
int fx=Find(x),fy=Find(y);
if(fx!=fy) p[fx]=fy;
}
void Kruskal()
{ int i,c,u,v;
Init(n);
ans=c=0;
for(i=0;i<t;i++){
u=e[i].x;
v=e[i].y;
if(Find(u)!=Find(v))//两个结点不在同一集合
{
ans=ans+e[i].d;
mrege(u,v);
c++;
}
if(c==n-1) return ;
}
}
int cmp(const void *a,const void *b)
{
struct node *aa=(struct node*)a,*bb=(struct node*)b;
return (*aa).d-(*bb).d;
}
int main()
{
int i,j,k;
char cs[2],ce[2];
while( scanf("%d",&n) && n)
{
t=0;
for(i=0;i<n-1;i++){
scanf("%s%d",cs,&k);
while(k--)
{
scanf("%s%d",ce,&j);
e[t].d=j;
e[t].x=cs[0]-'A';
e[t++].y=ce[0]-'A';
}
}
qsort(e,t,sizeof(e[0]),cmp);
Kruskal();
cout<<ans<<endl;
}
system("pause");
return 0;
}