原题地址:点击打开链接
用并查集实现克鲁斯卡尔算法,求最小生成树
#include<stdio.h>
#include<algorithm>
using namespace std;
struct Edge
{
int u;
int v;
int cost;
}e[1000];
int p[500];
int comp(Edge e1,Edge e2)
{
return e1.cost<e2.cost;
}
int find(int x)
{
if(p[x]!=x)
{
p[x]=find(p[x]);
}
return p[x];
}
bool bin(int x,int y)
{
int g=find(x);
int h=find(y);
if(g!=h)
{
p[g]=h;
return true;
}
return false;
}
bool check(int n)
{
int i,res=0;
for(i=1;i<=n;i++)
{
if(p[i]==i)
res++;
}
if(res>1)
return false;
return true;
}
int main()
{
int n,i,m,j,u,v,cost,size,res;
char ch[2];
while(scanf("%d",&n)&&n!=0)
{
res=0;
size=0;
for(i=1;i<=n;i++)
{
p[i]=i;
}
for(i=1;i<n;i++)
{
u=i;
getchar();
scanf("%s%d",&ch,&m);
for(j=0;j<m;j++)
{
getchar();
scanf("%s%d",&ch,&cost);
e[size].u=i;
e[size].v=ch[0]-'A'+1;
e[size++].cost=cost;
}
}
sort(e,e+size,comp);
for(i=0;i<size;i++)
{
if(bin(e[i].u,e[i].v))
{
res+=e[i].cost;
if(check(n))
break;
}
}
printf("%d\n",res);
}
return 0;
}