POJ 2420 A Star not a Tree? (爬山法||模拟退火)

来源:互联网 发布:linux shell 小数运算 编辑:程序博客网 时间:2024/05/21 08:08

爬山法+模拟退火:


#include<cstdio>#include<cstring>#include<iostream>#include<queue>#include<cmath>#include<math.h>#include<ctime>#include<cstdlib>using namespace std ;struct node{    double x,y;}q[120];double xx,yy;int n;double dis(double x,double y,node p){    return sqrt( (x-p.x)*(x-p.x)+(y-p.y)*(y-p.y) );}double getsum(double a,double b){    double tmp=0;    for(int i=0;i<n;i++)        tmp+=dis(a,b,q[i]);    return tmp;}int main(){    int m,i,j,k;    while(~scanf("%d",&n))    {        double ans;        xx=0,yy=0;double t=10000;        for(i=0;i<n;i++)        {            scanf("%lf%lf",&q[i].x,&q[i].y);            xx+=q[i].x;yy+=q[i].y;        }        xx/=n;yy/=n;        ans=getsum(xx,yy);        double tmp,x,y;        while(t>0.02)        {            x=y=0;            for(i=0;i<n;i++)            {                x+=(q[i].x-xx)/dis(xx,yy,q[i]);                y+=(q[i].y-yy)/dis(xx,yy,q[i]);            }            tmp=getsum(xx+x*t,yy+y*t);            if(tmp<ans)            {                ans=tmp;                xx+=x*t;yy+=y*t;            }            /*else if(log( (tmp-ans)/t)<(rand()%10000/10000.0) )//注意使用的cstdlib/ctime头文件            {                ans=tmp;                xx+=x*t;yy+=y*t;            }*////模拟退火和爬山就是一个else if(log(tmp-ans )/t<(rand()%10000)/10000.0 )的区别            t*=0.9;        }        printf("%.0lf\n",ans);    }    return 0;}


0 0
原创粉丝点击