【基础】随机优化算法

https://codeforces.com/contest/2/problem/C

    double X, Y;

    double dis(int id) {
        double len = sqrt(sq(X - x[id]) + sq(Y - y[id]));
        return PI / 2.0 - acos(r[id] / len);
    }

    double getRes() {
        double dis1 = dis(1), dis2 = dis(2), dis3 = dis(3);
        return sq(dis1 - dis2) + sq(dis1 - dis3) + sq(dis2 - dis3);
    }

    double myRand() {
        return (rand() >= RAND_MAX / 2) ? 1 : -1;
    }

    void InnerRandomOptimize(double step, int p1, int p2) {
        double curRes = getRes();
        for(int i = 1; i <= p1; ++i) {
            for(int j = 1; j <= p2; ++j) {
                double curx = X, cury = Y;
                X += myRand() * step;
                Y += myRand() * step;
                double newRes = getRes();
                if(newRes > curRes) {
                    X = curx;
                    Y = cury;
                } else
                    curRes = newRes;
            }
            step *= 0.85;
        }
    }

    void RandomOptimize() {
        InnerRandomOptimize(10, 20, 2000);
        InnerRandomOptimize(10, 200, 200);
        InnerRandomOptimize(10, 2000, 20);
    }
上一篇:C语言编程>第四周 ⑥ 利用#define命令求一个数的平方。


下一篇:一篇文章让你看懂顺序表(c)