$模擬退火$c++
$這種全局最優的問題用模擬退火$ide
$模擬退火就是每次向四周隨機移動,移動的幅度和溫度成正比,若是新的位置更優就接受,不然按必定機率接收,機率和溫度成正比$spa
$最後穩定後再在最優解附近蹦躂幾下看看有沒有更好的$code
$你問我這是什麼道理,我說無(我)可(不)奉(知)告(道)$blog
#include<bits/stdc++.h> using namespace std; const int N = 10005; struct P { double x, y, w; } p[N], ans; int n; double mn = 1e18, T = 100000; double rd() { return rand() % 10000 / 10000.0; } double sqr(double x) { return x * x; } double calc(P a) { double ret = 0; for(int i = 1; i <= n; ++i) { ret += sqrt(sqr(a.x - p[i].x) + sqr(a.y - p[i].y)) * p[i].w; } if(ret < mn) { mn = ret; ans = a; } return ret; } int main() { srand(19992147); scanf("%d", &n); for(int i = 1; i <= n; ++i) { scanf("%lf%lf%lf", &p[i].x, &p[i].y, &p[i].w); ans.x += p[i].x; ans.y += p[i].y; } ans.x /= n; ans.y /= n; P now = ans; while(T > 0.001) { P nw; nw.x = now.x + T * (rd() * 2 - 1.0); nw.y = now.y + T * (rd() * 2 - 1.0); double d = calc(now) - calc(nw); if(d > 0 || exp(d / T) > rd()) { now = nw; } T *= 0.991; } for(int i = 1; i <= 1000; ++i) { P nw; nw.x = ans.x + T * (rd() * 2 - 1.0); nw.y = ans.y + T * (rd() * 2 - 1.0); calc(nw); } printf("%.3f %.3f\n", ans.x, ans.y); return 0; }