POJ.2420.A Star not a Tree.模擬退火.0ms

http://poj.org/problem?id=2420
題目大意:
給出平面上n個點,求到所有點距離和最短的點,輸出該距離和。

代碼:

#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <string.h>
#include <time.h>

struct pos{ double x, y; } *P, city[101];
int n;

///////// 計算點x到各點距離之和 /////////////
double dis(struct pos * x){
    double d = 0;
    for (P = city + n - 1; P >= city; P--)
        d += hypot(P->x - x->x, P->y - x->y);
    return d;
}

///////// 模擬退火 /////////////
double SA(){
    double t, min, tmp;     // 溫度,最小距離,臨時距離
    struct pos p, tp;       // 最優點,臨時點
    int k = 0;                  // 記錄連續未接受點數

    p.x = p.y = 5000;       // 初始化最優點爲中心點
    min = dis(&p);          
    srand((unsigned)&t);

    ///// 初始化溫度,溫度以一定速率減小,溫度小於臨界(1) 或 連續超過一定數量(20)個臨時點未被接受時 終止 /////
    for (t = 5000; t > 1 && k++ < 20; t *= .93){

        ///// 在p周圍一定 範圍 內生成臨時點, 該範圍隨溫度t降低逐漸減小 /////
        tp.x = p.x + (rand() & 1 ? 1 : -1) * rand()*t / RAND_MAX;
        tp.y = p.y + (rand() & 1 ? 1 : -1) * rand()*t / RAND_MAX;
        tmp = dis(&tp);

        ///// 若生成的臨時點距離小於當前最小,更新最優點 /////
        ///// 否則,以一定 概率 接受該臨時點,該概率隨溫度t降低逐漸減小 /////
        if (tmp < min || rand()*10000./RAND_MAX < t){
            p = tp;
            min = tmp;
            k = 0;
        }
    }
    return min;
}

int main()
{
    scanf("%d",&n);
    for (int i = 0; i < n; i++)
        scanf("%lf%lf", &city[i].x, &city[i].y);
    printf("%.0f\n", SA());
    return 0;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章