Time Limit: 1000 MS Memory Limit: 131072 KB
Description
lmh is now doing a math problem, known to have the coordinates of n points, find the shortest distance to connect the n points, can you give him some advice?
Input
The first line contains 0 < n <= 1000, the number of point. For each point, a line follows; each following line contains two real numbers indicating the (x,y) coordinates of the point.
Output
The shortest distance.prints a single real number to two decimal places.
Sample Input
3
1.0 1.0
2.0 2.0
2.0 4.0
Sample Output
3.41
Prim算法是一种求最小生成树的算法,这一算法通常被用在稠密图中,稀疏图中求最小生成树常用Kruskal算法。
这种算法的实现方式是:先任选一个点作为起始点,然后从与它直接相连的点中选出一个到它距离最小的点,将这一点和起始点绑在一起当作一个整体,然后再从与这个整体直接相连的点中选出一个到这个整体距离最小的点,然后将这个点加入这个整体,后面以此类推,由于一开始选定了起始点,那么只需要再将n-1个点加入整体即可结束算法。
代码如下:
#include<iostream>
#include<cstdio>
#include<cstring>
#include<cmath>
using namespace std;
const int inf=999999999;//自定一个最大值
bool vis[1005];
double dist[1005],graph[1005][1005];//dist数组表示当前已经选中的各点这个大集合和其他没被选中且与集合直接相连的各点之间的最小距离
struct point{
double x;
double y;
}dat[1005];//坐标结构体数组
double dis(point a,point b)//计算距离的函数
{
return (sqrt((b.y-a.y)*(b.y-a.y)+(b.x-a.x)*(b.x-a.x)));
}
void init(int n)//初始化图的邻接矩阵
{
memset(vis,0,sizeof(vis));
for(int i=1;i<=n;++i)
{
for(int j=1;j<=n;++j)
{
if(i==j) graph[i][j]=0;
else graph[i][j]=inf;
}
}
}
double prim(int n)
{
int order;
double sum=0,minn;
for(int i=1;i<=n;++i)
{
dist[i]=graph[1][i];//假定从1号点开始选,那么集合中只有1号点,那么此时dist数组的含义就是1号点到其余与其直接相连的点的最短距离
}
vis[1]=1;
for(int i=1;i<n;++i)
{
minn=inf;
for(int j=1;j<=n;++j)
{
if(!vis[j]&&dist[j]<minn)
{
order=j;
minn=dist[j];//挑选出没被选中的各点中到大集合的距离最小的点
}
}
//cout<<sum<<endl;
vis[order]=1;
sum+=dist[order];
for(int j=1;j<=n;++j)
{
if(!vis[j]&&dist[j]>graph[order][j])
dist[j]=graph[order][j];//这步是在动态改变与集合直接相连的各点到已经选中的点的这个大集合的最短距离
}
}
return sum;
}
int main()
{
int n;
while(scanf("%d",&n)!=EOF)
{
init(n);
for(int i=1;i<=n;++i)
{
scanf("%lf %lf",&dat[i].x,&dat[i].y);
//cin>>dat[i].x>>dat[i].y;
}
for(int i=1;i<=n;++i)
{
for(int j=1;j<=n;++j)
{
graph[i][j]=dis(dat[i],dat[j]);//计算距离并存为点
}
}
printf("%.2lf\n",prim(n));
}
return 0;
}