题目描述
In an episode of the Dick Van Dyke show, little Richie connects the freckles on his Dad’s back to form a picture of the Liberty Bell. Alas, one of the freckles turns out to be a scar, so his Ripley’s engagement falls through.
Consider Dick’s back to be a plane with freckles at various (x,y) locations. Your job is to tell Richie how to connect the dots so as to minimize the amount of ink used. Richie connects the dots by drawing straight lines between pairs, possibly lifting the pen between lines. When Richie is done there must be a sequence of connected lines from any freckle to any other freckle.
输入
The first line contains 0 < n <= 100, the number of freckles on Dick’s back. For each freckle, a line follows; each following line contains two real numbers indicating the (x,y) coordinates of the freckle.
输出
Your program prints a single real number to two decimal places: the minimum total length of ink lines that can connect all the freckles.
样例输入
3
2723.62 7940.81
8242.67 11395.00
4935.54 6761.32
9
10519.52 11593.66
12102.35 2453.15
7235.61 10010.83
211.13 4283.23
5135.06 1287.85
2337.48 2075.61
6279.72 13928.13
65.79 1677.86
5324.26 125.56
0
样例输出
8199.56
32713.73
思路:求出每个点到点之间的距离,最后用Kruscal或者是Prim算法求出最小生成树即可,但是在Codeup上过不了,在牛客网上可以过,应该是精度的问题,第二个笔者的答案是32713.74,上网测试过很多博主的代码,答案都是这个。
#include <iostream>
#include <algorithm>
#include <cmath>
using namespace std;
const int MAXV = 110;
const double INF = 1000000000;
int n;
double d[MAXV], G[MAXV][MAXV];
bool vis[MAXV] = {0};
struct node { //点的坐标
double x, y;
}weight[MAXV];
double getLength(node a, node b) { //获取点与点之间的距离
return sqrt((a.x - b.x) * (a.x - b.x) + (a.y - b.y) * (a.y - b.y));
}
double prim() {
fill(d, d + MAXV, INF);
double ans = 0;
d[0] = 0;
for(int i = 0; i < n; i++) {
int u = -1;
double MIN = INF;
for(int j = 0; j < n; j++) {
if(!vis[j] && d[j] < MIN) {
MIN = d[j];
u = j;
}
}
if(u == -1) return -1;
vis[u] = true;
ans += d[u];
for(int v = 0; v < n; v++) {
if(!vis[v] && G[u][v] < d[v]) d[v] = G[u][v];
}
}
return ans;
}
int main()
{
while(scanf("%d", &n), n != 0) {
fill(G[0], G[0] + MAXV * MAXV, INF);
fill(vis, vis + MAXV, 0);
for(int i = 0; i < n; i++)
scanf("%lf%lf", &weight[i].x, &weight[i].y);
for(int i = 0; i < n - 1; i++)
for(int j = i + 1; j < n; j++) {
G[i][j] = getLength(weight[i], weight[j]);
G[j][i] = G[i][j];
}
printf("%.2lf\n", prim());
}
return 0;
}
本文介绍了一种利用Prim算法解决连接多个点以最小化总连线长度的问题。通过计算平面上各点间的距离,并运用Prim算法找出最小生成树,从而实现用最少的‘墨水’将所有点连接起来的目标。
342

被折叠的 条评论
为什么被折叠?



