poj2420 A Star not a Tree?【模拟退火】

题目大意:

给定n个点,求一点到所有点距离的最小值。

解题思路:

模拟退火真是神,
一般的爬山算法就是先设置一个起始点较大的步长step(初始温度),每次随机向一个方向走step,若该点更优,则更新答案,并转移起始点位置。操作完后减小等比例减小step重复上述操作若干次(尽量多),则可得到近似最优解。即:每次都往更优的地方走。
而模拟退火只是在爬山算法的基础上有一定概率往劣处走。

#include<cstdio>
#include<algorithm>
#include<cmath>
using namespace std;

int read()
{
    int i=0,f=1;char c;
    for(c=getchar();(c<'0'||c>'9')&&c!='-';c=getchar());
    if(c=='-')f=-1,c=getchar();
    for(;c>='0'&&c<='9';c=getchar())i=(i<<3)+(i<<1)+c-'0';
    return i*f;
}

const int N=105;
struct point
{
    double x,y;
    point(){}
    point(double _x,double _y):x(_x),y(_y){}
    inline friend point operator - (const point &a,const point &b)
    {return point(a.x-b.x,a.y-b.y);}
    inline double dis(){return sqrt(x*x+y*y);}
}p[N];
int n;

double calc(point a)
{
    double res=0;
    for(int i=1;i<=n;i++)res+=(p[i]-a).dis();
    return res;
}

int main()
{
    //freopen("lx.in","r",stdin);
    n=read();
    for(int i=1;i<=n;i++)p[i].x=read(),p[i].y=read();
    double ans=1e20,step=10000;point s=p[1];
    while(step>1e-10)
    {
        double ang=rand()%314;
        point t=point(s.x+step*cos(ang),s.y+step*sin(ang));
        double D=calc(t);
        if(D<ans)s=t,ans=D;
        else
        {
            if(exp((D-ans)/step)<(rand()%10000)/10000.0)  
                ans=D,s=t;
        }
        step*=0.99;
    }
    printf("%.0f",ans);
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值