CF2C Commentator problem

不同于模拟退火的一种优化算法

我本来一看到这道题就打了个模拟退火,但是死活模拟不对,样例死活过完就是重心。

翻题解发现可以用向四周的步长移动来求出最优解。不知道这叫什么名字但肯定不是模拟退火。

算法的思想是这样的:

给出4个方向上下左右,然后初始化步长,如果当前新答案比老答案好就更新这个答案,否则步长变短一半。步长变为0停止。

算出来的就是答案。。。

代码:


#include<cstdio>
#include<cmath>
#include<cstdlib>
const double eps = 1e-6;
const int dx[] = {0, 1, -1, 0, 0};
const int dy[] = {0, 0, 0, 1, -1};
struct Circle
{
    int x, y, r;
} cir[4];

double ansx, ansy, ans;

double dist(double x, double y, double xx, double yy)
{
    return sqrt((x - xx) * (x - xx) + (y - yy) * (y - yy));
}
double cal(double x, double y)
{
    double res = 0;
    double g[4];
    for(int i = 1; i <= 3; i++) g[i] = dist(x, y, cir[i].x, cir[i].y) / cir[i].r;
    res += (g[1] - g[2]) * (g[1] - g[2]);
    res += (g[2] - g[3]) * (g[2] - g[3]);
    res += (g[3] - g[1]) * (g[3] - g[1]);
    return res / 3;
}
int main()
{
    srand(19260817);
    for(int i = 1; i <= 3; i++) scanf("%d%d%d", &cir[i].x, &cir[i].y, &cir[i].r);
    ansx = (cir[1].x + cir[2].x + cir[3].x) / 3.0;
    ansy = (cir[1].y + cir[2].y + cir[3].y) / 3.0;
    ans = cal(ansx, ansy);
    double T = 1;
    while(T > eps)
    {
        int dir = -1;
        for(int i = 1; i <= 4; i++)
        {
            double res = cal(ansx + dx[i] * T, ansy + dy[i] * T);
            if(res < ans) ans = res, dir = i;
        }
        if(dir == -1) T /= 2;
        else ansx += dx[dir] * T, ansy += dy[dir] * T;
    }
    if(ans < eps) printf("%.5lf %.5lf\n", ansx, ansy);
    return 0;
}

转载于:https://www.cnblogs.com/Garen-Wang/p/9873612.html

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值