POJ 2420 (模拟退火)

水题,四个方向搜索。

#include <cstring>
#include <cstdio>
#include <cmath>
#include <algorithm>
using namespace std;
#define maxn 111
#define delta 0.98 //温度下降速度
#define init_T 100 //初始温度
#define INF 1e30
#define eps 1e-8
#define move Move

struct point {
    double x, y;
}p[maxn];
const int move[4][2] = {{1, 1}, {1, -1}, {-1, 1}, {-1, -1}};
int n;

double dis (point a, point b) {
    double xx = a.x-b.x, yy = a.y-b.y;
    return sqrt (xx*xx + yy*yy);
}

double sum (point from) { //这个点到其他所有点的距离
    double ans = 0;
    for (int i = 1; i <= n; i++) {
        ans += dis (p[i], from);
    }
    return ans;
}

void solve () {
    point from = p[1];
    double t = init_T;
    double ans = INF;
    while (t > eps) {
        bool flag = 1;
        while (flag) {
            flag = 0;
            point next;
            for (int i = 0; i < 4; i++) {
                next.x = from.x + move[i][0]*t;
                next.y = from.y + move[i][1]*t;
                double cur = sum (next);
                if (cur < ans) {
                    ans = cur;
                    flag = 1;
                    from = next;
                }
            }
        }
        t *= delta;
    }
    printf ("%.0f\n", ans);
}

int main () {
    //freopen ("in", "r", stdin);
    while (scanf ("%d", &n) == 1) {
        for (int i = 1; i <= n; i++) {
            scanf ("%lf%lf", &p[i].x, &p[i].y);
        }
        solve ();
    }
    return 0;
}


你可能感兴趣的:(POJ 2420 (模拟退火))