Problem Description
Eddy begins to like painting pictures recently ,he is sure of himself to become a painter.Every day Eddy draws pictures in his small room, and he usually puts out his newest pictures to let his friends appreciate. but the result it can be imagined, the friends are not interested in his picture.Eddy feels very puzzled,in order to change all friends 's view to his technical of painting pictures ,so Eddy creates a problem for the his friends of you.
Problem descriptions as follows: Given you some coordinates pionts on a drawing paper, every point links with the ink with the straight line, causes all points finally to link in the same place. How many distants does your duty discover the shortest length which the ink draws?
Input
The first line contains 0 < n <= 100, 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.
Input contains multiple test cases. Process to the end of file.
Output
Your program prints a single real number to two decimal places: the minimum total length of ink lines that can connect all the points.
Sample Input
3
1.0 1.0
2.0 2.0
2.0 4.0
Sample Output
3.41
【分析】prim算法就最小生成树计科,map数组使用两点间距离公式初始化。
【代码】
//1162 Eddy's picture
// 最小生成树 题
//Prim算法
#include <bits/stdc++.h>
#include <stdio.h>
#include <math.h>
using namespace std;
double dis[105][105];
struct Point
{
double x,y;
}p[105];
int visit[105]={0};
double d[105];
int n;
double prim(int cur)//首个挑选到的节点 cur
{
int index = cur;
double sum = 0; //最短路径之和
int i = 0 , j = 0;
// cout << index << " ";
memset(visit,false, sizeof(visit)); //标记数组,初始化,全部未访问
visit[cur] = true;
for(i = 1; i <= n; i++)//与第一个挑走的点i,相连的所有边的距离,存入dist[]中
d[i] = dis[cur][i];//初始化,每个与a邻接的点的距离存入dist
for(i = 2; i <= n; i++)//遍历表中每一个节点
{
double minn= 999999999; //与另一个表相连的最小边,初始化,为一个极大值
for(j = 1; j <= n; j++)
{
if(!visit[j] && d[j] < minn) //找到未访问的点中,距离当前最小生成树距离最小的点
{
minn = d[j]; //不断更新与点cur的相连点的最短距离
index = j;
}
}
visit[index] = true;//标记距离最短的刚刚被拿走的那个节点,已经被访问过
// cout << index << " ";
sum += minn;
for(j = 1; j <= n; j++) //已经进入最小树的点的可及范围,与刚进入最小树的点相比较,比之前点可到达某点的距离较小,更新当前最小生成树的可及范围的最小值*****
{
if(!visit[j] && d[j]>dis[index][j]) //执行更新,如果点距离当前点的距离更近,就更新dist
{
d[j] = dis[index][j];
}
}
}
// cout << endl;
return sum; //返回最小生成树的总路径值
}
int main()
{
while(scanf("%d",&n)!=EOF)
{
for(int i=1;i<=n;i++)
{
float a,b;
cin>>p[i].x>>p[i].y;
}
for(int i=1;i<=n;i++)
{
for(int j=1;j<=n;j++)
{
dis[i][j]=sqrt((p[i].x-p[j].x)*(p[i].x-p[j].x)+(p[i].y-p[j].y)*(p[i].y-p[j].y));
}
}
double ans=prim(1);
printf("%.2f\n",ans);
}
return 0;
}