題意:空間中有 n(3 <= n <= 100) 個點(0.00 <= ai, bi, ci <= 1000.00),求到這 n 個點的距離之和最短的一點。
題目鏈接:http://acm.zju.edu.cn/onlinejudge/showProblem.do?problemCode=2928
——>>如果是一維的,那麼答案是中位數;現在是三維的,賽時不會,賽後學了一種叫做爬山的隨機算法用於這題。
爬山算法:先選取其中一值作爲最優值,然後向該值附近掃描,若發現更優的值,則以該更優值作爲最優值,繼續迭代掃描;否則所選值已是最優值。。
此題我以(0, 0, 0)作爲初始最優值,然後往其27個可前進方向移動尋找更優值。
精度的設置要特別小心。。1e-8的精度過不了。。
#include <cstdio>
#include <cmath>
const int MAXN = 100 + 10;
const int MAXD = 30;
const int INF = 0x3f3f3f3f;
const double EPS = 1e-12;
const double rate = 0.99;
int n;
int dx[MAXD];
int dy[MAXD];
int dz[MAXD];
int dcnt;
double a[MAXN];
double b[MAXN];
double c[MAXN];
double A, B, C;
void Read()
{
for (int i = 0; i < n; ++i)
{
scanf("%lf%lf%lf", a + i, b + i, c + i);
}
}
void getDirection()
{
dcnt = 0;
for (int i = -1; i <= 1; ++i)
{
for (int j = -1; j <= 1; ++j)
{
for (int k = -1; k <= 1; ++k)
{
dx[dcnt] = i;
dy[dcnt] = j;
dz[dcnt] = k;
++dcnt;
}
}
}
}
int Dcmp(double x)
{
if (fabs(x) < EPS) return 0;
return x > 0 ? 1 : -1;
}
void Solve()
{
double step = 1000;
double minDistance = INF;
A = B = C = 0;
getDirection();
while (Dcmp(step) != 0)
{
for (int i = 0; i < dcnt; ++i)
{
double newx = A + dx[i] * step;
double newy = B + dy[i] * step;
double newz = C + dz[i] * step;
double sumOfDistance = 0;
if (Dcmp(newx) < 0 || Dcmp(newx - 1000) > 0 ||
Dcmp(newy) < 0 || Dcmp(newy - 1000) > 0 ||
Dcmp(newz) < 0 || Dcmp(newz - 1000) > 0) continue;
for (int j = 0; j < n; ++j)
{
sumOfDistance += sqrt((a[j] - newx) * (a[j] - newx) + (b[j] - newy) * (b[j] - newy) + (c[j] - newz) * (c[j] - newz));
}
if (Dcmp(sumOfDistance - minDistance) < 0)
{
minDistance = sumOfDistance;
A = newx;
B = newy;
C = newz;
}
}
step *= rate;
}
}
void Output()
{
printf("%.3f %.3f %.3f\n", A, B, C);
}
int main()
{
while (scanf("%d", &n) == 1)
{
Read();
Solve();
Output();
}
return 0;
}