标签:blog http os io for 2014 amp log
//hnldyhy(303882171) 8:54:04
#include <iostream> // poj 1258
#include <algorithm>
using namespace std;
#define N 105
int p[N];
void init (int n)
{ for (int i=1;i<=n;i++) p[i]=i; }
int find(int x)
{
if (p[x]==x)return x;
else return p[x]=find(p[x]);
}
void merge(int x,int y)
{
int a=find(x),b=find(y);
if (a!=b) p[a]=b;
}
int a[N][N],t,ans,n;
struct edge
{ int x1,x2,d; } e[N*(N-1)/2]; // N个顶点 N(N-1)/2 边的条数
int cmp(const void *a,const void *b)
{
struct edge *aa=(struct edge *)a,
*bb=(struct edge *)b ;
return (*aa).d-(*bb).d;
}
void kruscal()
{ int u,v,i,c=0;
init (n); ans=0;
for (i=0;i<t;i++)
{ u=e[i].x1; v=e[i].x2;
if (find(u)!=find(v)) //不在同一个集合
{ ans=ans+e[i].d; merge(u,v); c++;}
if (c==n-1) return ;
}
}
int main()
{ int i,j;
while (cin>>n&&n>=3)
{ for (i=1;i<=n;i++)
for (j=1;j<=n;j++)
cin>>a[i][j]; t=0;
for (i=2;i<=n;i++)
for (j=1;j<i;j++)
{ e[t].x1=i; e[t].x2=j;
e[t].d=a[i][j]; t++; }
qsort(e,t,sizeof(e[0]),cmp);
kruscal();
cout<<ans<<endl;
}
return 0;
}
poj 1258 kruscal,布布扣,bubuko.com
标签:blog http os io for 2014 amp log
原文地址:http://www.cnblogs.com/2014acm/p/3905519.html