zoj - 2928 - Mathematical contest in modeling(爬山)

题意:空间中有 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;
}



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值