/*
Made by Karen
16:40p.m. at Mar.4,2012
prim算法求最小生成树
同hdu1875 而且在main函数里面的处理更简单
*/
#include <iostream>
#include <cstdio>
#include <math.h>
using namespace std;
#define MAX_Point 110
#define MAX_Edge 12100
#define INF 99999999
double arr_list[110][110];
struct point
{
double x;
double y;
}point[MAX_Point];
struct Edge
{
int pointer;
double lowcost;
int flag;
}edge[MAX_Edge];
double prim(int n)
{
int i,j,k=1,flag;
double min,sum2=0;
j=1;
for(i=1;i<=n;i++)
{
edge[i].pointer=i;
edge[i].lowcost=arr_list[j][i];
edge[i].flag=0;
}
edge[j].flag=1;
edge[j].lowcost=0;
for(i=2;i<=n;i++)
{
k=1;
min=INF;
flag=0;
for(j=2;j<=n;j++)
{
if(edge[j].flag==0&&edge[j].lowcost<min)
{
k=j;
min=edge[j].lowcost;
flag=1;
}
}
if(!flag) return -1;
edge[k].flag=1;
sum2+=min;
for(j=2;j<=n;j++)
{
if(edge[j].flag==0&&arr_list[k][j]<edge[j].lowcost)
{
edge[j].pointer=k;
edge[j].lowcost=arr_list[k][j];
}
}
}
return sum2;
}
int main()
{
int n,i,j;
double tmp,ans;
while(scanf("%d",&n)!=EOF)
{
for(i=0;i<=100;i++)
for(j=0;j<=100;j++)
arr_list[i][j]=INF;
for(i=1;i<=n;i++)
scanf("%lf%lf",&point[i].x,&point[i].y);
for(i=1;i<=n;i++)
for(j=1;j<=n;j++)
{
tmp=sqrt((point[i].x-point[j].x)*(point[i].x-point[j].x)+(point[i].y-point[j].y)*(point[i].y-point[j].y));
arr_list[i][j]=tmp;
}
ans=prim(n);
printf("%.2lf\n",ans);
}
return 0;
}
hdu1162最小生成树
最新推荐文章于 2018-10-11 14:30:44 发布