题意很简单:就是有N个节点的带权图,让你找最小生成树;
这里写代码片
#include<cstdio>
#include<iostream>
#include<cstring>
#include<algorithm>
using namespace std;
int fa[105],a[105][105];
struct T
{
int r,l,data;
}b[5005];
int Find(int x)
{
return x==fa[x]?x:fa[x]=Find(fa[x]);
}
bool cmp(T x,T y)
{
return x.data<y.data;
}
void Union(int x,int y)
{
int fx=Find(x);
int fy=Find(y);
fa[fx]=fy;
}
int main()
{
int i,j,k,ans,n,xx,yy,cx=0;
while(~scanf("%d",&n)&&n)
{
k=0;
for(i=1;i<=n;i++)
{
fa[i]=i;
for(j=1;j<=n;j++)
{
scanf("%d",&a[i][j]);
if(i<j)
{
b[k].data=a[i][j];
b[k].r=i;
b[k].l=j;
k++;
}
}
}
sort(b,b+k,cmp);
ans=0;
cx=0;
for(i=0;i<k;i++)
{
if(cx==n-1)
break;
xx=Find(b[i].r);
yy=Find(b[i].l);
if(xx!=yy)
{
Union(xx,yy);
ans+=b[i].data;
cx++;
}
}
printf("%d\n",ans);
}
return 0;
}