您的位置:首页 > 其它

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

2015-11-24 11:28 399 查看
爬山法+模拟退火:

#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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  模拟退火