爬山算法、模拟退火算法

参考:http://www.cnblogs.com/heaad/archive/2010/12/20/1911614.html#!comments

http://blog.csdn.net/acdreamers/article/details/10019849


1、POJ 2420 A Star not a Tree?

#include <iostream>
#include <cstdio>
#include <cstring>
#include <cstdlib>
#include <algorithm>
#include <queue>
#include <vector>
#include <stack>
#include <map>
#include <set>
#include <cmath>
#include <cctype>
#include <ctime>
#include <cassert>

using namespace std;

#define REP(i, n) for (int i = 0; i < (n); ++i)
#define eps 1e-9

typedef long long ll;
typedef pair<int, int> Pair;

const int INF = 0x7fffffff;
const int maxn = 100 + 10;

struct Node {
    double x, y;
};

int n;
int dir[][2] = {{1, 0}, {-1, 0}, {0, 1}, {0, -1}};
Node node[maxn];
double x_sum = 0.0, y_sum = 0.0, x_average = 0.0, y_average = 0.0;

double dis(Node a, Node b);
double get_sum(Node a);
double Search(void);

int main() {
#ifdef __AiR_H
    freopen("in.txt", "r", stdin);
#endif // __AiR_H
    scanf("%d", &n);
    REP(i, n) {
        scanf("%lf %lf", &node[i].x, &node[i].y);
        x_sum += node[i].x; y_sum += node[i].y;
    }
    x_average = x_sum / n; y_average = y_sum / n;
    printf("%.0f\n", Search());
#ifdef __AiR_H
    printf("Time used = %.2fs\n", (double)clock() / CLOCKS_PER_SEC);
#endif // __AiR_H
    return 0;
}

double Search(void) {
    Node start, t; start.x = x_average; start.y = y_average;
    double T = 100.0, ans = get_sum(start), ans_t;
    while (T > eps) {
        bool flag = true;
        while (flag) {
            flag = false;
            REP(i, 4) {
                t.x = start.x + dir[i][0] * T; t.y = start.y + dir[i][1] * T;
                ans_t = get_sum(t);
                if (ans_t < ans) { ans = ans_t; start = t; flag = true; }
            }
        }
        T *= 0.9;
    }
    return ans;
}

double get_sum(Node a) {
    double ret = 0.0;
    REP(i, n) { ret += dis(node[i], a); }
    return ret;
}

double dis(Node a, Node b) {
    return sqrt((a.x - b.x) * (a.x - b.x) + (a.y - b.y) * (a.y - b.y));
}






评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值