#include<cstdio>
#include<iostream>
#include<string>
#include<algorithm>
#include<math.h>
using namespace std;
const int maxn=100;
struct Edge
{
int from;
int to;
double length;
bool operator<(const Edge &e)const{
return length<e.length;
}
};
struct node
{
double x;
double y;
};
Edge edge[maxn*maxn];
int father[maxn];
int height[maxn];
node zui[maxn];
void Initial(int n)
{
for(int i=0;i<=n;i++)
{
father[i]=i;
height[i]=0;
}
}
int Find(int x)
{
if(x!=father[x])
{
father[x]=Find(father[x]);
}
return father[x];
}
void Union(int x,int y)
{
x=Find(x);
y=Find(y);
if(x!=y)
{
if(height[x]<height[y])
{
father[x]=y;
}else if(height[y]<height[x])
{
father[y]=x;
}else
{
father[y]=x;
height[x]++;
}
}
return;
}
double kruskal(int n,int edgeNumber)
{
Initial(n);
sort(edge,edge+edgeNumber);
double sum=0.0;
for(int i=0;i<edgeNumber;++i)
{
Edge current=edge[i];
if(Find(current.from)!=Find(current.to))
{
Union(current.from,current.to);
sum+=current.length;
}
}
return sum;
}
int main()
{
int n;
while(scanf("%d",&n)!=EOF)
{
if(n==0)
{
break;
}
for(int i=1;i<=n;i++)
{
scanf("%lf%lf",&zui[i].x,&zui[i].y);
}
int edgeNumber=n*(n-1)/2;
int cc=0;
for(int i=1;i<n;i++)
{
for(int j=i+1;j<=n;j++)
{
edge[cc].from=i;
edge[cc].to=j;
edge[cc++].length=sqrt((zui[i].x-zui[j].x)*(zui[i].x-zui[j].x)+(zui[i].y-zui[j].y)*(zui[i].y-zui[j].y));
}
}
double answer=kruskal(n,edgeNumber);
printf("%.2lf\n",answer);
}
return 0;
}
Freckles最小生成树
猜你喜欢
转载自blog.csdn.net/baidu_37143827/article/details/104707130
今日推荐
周排行