题目大意:有n个球,给你每个球的坐标(x、y、z)和半径(r),求把每个球连起来最小需要多少花费(距离)
基本上是最小生成树的模板题了(精度很恶心 自己注意吧)
两个球之间的距离是sqrt(pow(x1-x2,2)+pow(y1-y2,2)+pow(z1-z2,2))-r1-r2;
附AC代码
#include<iostream>
#include<math.h>
using namespace std;
double Map[101][101];
bool Mark[101];
struct Point
{
double x, y, z, r;
};
double CalValue(Point nPoint_1, Point nPoint_2)
{
double value = (double)sqrt(pow(nPoint_1.x - nPoint_2.x, 2) + pow(nPoint_1.y - nPoint_2.y, 2) + pow(nPoint_1.z - nPoint_2.z, 2));
value = (double)value - nPoint_1.r;
value = (double)value - nPoint_2.r;
if (value <= 0.0)
{
return 0.0;
}
return value;
}
int main()
{
int n;
while (cin >> n&&n)
{
memset(Map, 0.0, sizeof(Map));
memset(Mark, false, sizeof(Mark));
Point *ArrPoint = new Point[n];
for (int i = 0; i < n; i++)
{
cin >> ArrPoint[i].x >> ArrPoint[i].y >> ArrPoint[i].z >> ArrPoint[i].r;
}
for (int i = 0; i < n; i++)
{
Map[i][i] = 100000.0;
for (int j = i+1; j < n; j++)
{
double Value = CalValue(ArrPoint[i], ArrPoint[j]);
Map[i][j] = Value;
Map[j][i] = Value;
}
}
double *ArrTemp = new double[n];
ArrTemp[0] = 0.0;
for (int i = 1; i < n; i++)
{
ArrTemp[i] = Map[0][i];
}
Mark[0] = true;
double fAns = 0.0;
for (int i = 0; i < n; i++)
{
int k = -1;
double nMin = -1;
for (int j = 0; j < n; j++)
{
if ((k == -1 || nMin >= ArrTemp[j])&&!Mark[j])
{
nMin = ArrTemp[j];
k = j;
}
}
if (k == -1)
{
break;
}
Mark[k] = true;
fAns += nMin;
for (int j = 0; j < n; j++)
{
if (ArrTemp[j] > Map[k][j])
{
ArrTemp[j] = Map[k][j];
}
}
ArrTemp[k] = 0.0;
}
printf("%.3lf\n", fAns);
delete[] ArrPoint;
delete[] ArrTemp;
}
return 0;
}