POJ,2420 A Star not a Tree?(模拟退火算法)

本文介绍了一种使用模拟退火算法解决平面上寻找一点使得该点到其它多个固定点的距离之和最小的问题。通过随机扰动及接受准则来逐步逼近最优解。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题意:平面上给你n个点,让你求一个点,到这n点的距离和最小。

分析:模拟退火算法。




#include <iostream>
#include<cstdio>
#include<ctime>
#include<cmath>
#include<cstdlib>
using namespace std;
#define N 1005
#define INF 1e20
#define D 25
#define EPS 1e-3
double a[N],b[N];
int mo[8][2]={1,0,0,1,-1,0,0,-1,1,-1,-1,1,-1,-1,1,1};
int main()
{
    int m;
    srand((unsigned int)time(NULL));
    while(~scanf("%d",&m))
    {
        for(int i=0;i<m;i++)
        {
            scanf("%lf%lf",&a[i],&b[i]);
        }
        double T=10001;
         double  ansx=(double)(rand()%1000+1)/1000.000*10000;
          double ansy=(double)(rand()%1000+1)/1000.000*10000;
        double ansdis=0;
        for(int i=0;i<m;i++)
            {
               ansdis=ansdis+sqrt((ansx-a[i])*(ansx-a[i])+(ansy-b[i])*(ansy-b[i]));
            }
        while(T>EPS)
        {
            for(int k=0;k<D;k++){
            for(int j=0;j<8;j++){
            double tempx=ansx+(double)(rand()%1000+1)/1000.000*T*mo[j][0];
            double tempy=ansy+(double)(rand()%1000+1)/1000.000*T*mo[j][1];
            if(tempx<0||tempx>10000||tempy<0||tempy>10000)
                continue;
            double tempdis=0;
            for(int i=0;i<m;i++)
            {
               tempdis=tempdis+sqrt((tempx-a[i])*(tempx-a[i])+(tempy-b[i])*(tempy-b[i]));
            }
            if(tempdis<ansdis)
            {
                ansx=tempx;
                ansy=tempy;
                ansdis=tempdis;
            }
            }
            }
            T=T*0.9;
        }
        printf("%.0f\n",ansdis);

    }
    return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值