#include <cstdio>
#include <iostream>
#include <algorithm>
#include <cmath>
#define INF 1000000.0
#define MAXN 102
using namespace std;
//最小生成树
double map[MAXN][MAXN],dist[MAXN];
double px[MAXN],py[MAXN];
int visited[MAXN];
double distans(double x1,double x2,double y1,double y2)
{
return sqrt((x1-x2)*(x1-x2)+(y1-y2)*(y1-y2));
}
double prim(int n)
{
int i,j,u;
double min,sum=0.0;
for (i=1;i<=n;i++)
{
dist[i]=map[1][i];
visited[i]=0;
}
visited[1]=1;
dist[1]=0.0;
for (i=2;i<=n;i++)
{
min=INF;
u=1;
for(j=1;j<=n;j++)
if(!visited[j]&&dist[j]<min)
{
min=dist[j];
u=j;
}
visited[u]=1;
sum+=min;
for(j=1;j<=n;j++)
if(!visited[j]&&dist[j]>map[u][j])
dist[j]=map[u][j];
}
return sum;
}
int main()
{
int n,i,j;
double ans;
while(scanf("%d",&n)!=EOF)
{
for(i=1;i<=n;i++)
scanf("%lf %lf",&px[i],&py[i]);
for (i=1;i<=n;i++)
{
for (j=i;j<=n;j++)
{
map[i][j]=map[j][i]=distans(px[i],px[j],py[i],py[j]);
}
}
ans=prim(n);
printf("%.2lf\n",ans);
}
return 0;
}
hdu1162 Eddy's picture (prim最小生成树)
最新推荐文章于 2021-07-28 20:12:48 发布