首页 > 其他 > 详细

poj 2420 A Star not a Tree? —— 模拟退火

时间:2018-10-30 15:44:55      阅读:163      评论:0      收藏:0      [点我收藏+]

题目:http://poj.org/problem?id=2420

给出 n 个点的坐标,求费马点;

模拟退火上。

代码如下:

#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<cstdlib>
#include<ctime>
#include<cmath>
#define eps 1e-17
#define dt 0.99
using namespace std;
typedef double db;
int const xn=105;
int n,xx[xn],yy[xn];
db ansx,ansy,ans;
int rd()
{
  int ret=0,f=1; char ch=getchar();
  while(ch<0||ch>9){if(ch==0)f=0; ch=getchar();}
  while(ch>=0&&ch<=9)ret=(ret<<3)+(ret<<1)+ch-0,ch=getchar();
  return f?ret:-ret;
}
db dist(db x,db y,db a,db b){return sqrt((x-a)*(x-a)+(y-b)*(y-b));}
db cal(db x,db y)
{
  db ret=0;
  for(int i=1;i<=n;i++)ret+=dist(x,y,xx[i],yy[i]);
  return ret;
}
void SA()
{
  db T=10000,x=ansx,y=ansy,lst=ans,tx,ty,tmp;
  while(T>eps)
    {
      tx=x+(rand()*2-RAND_MAX)*T;
      ty=y+(rand()*2-RAND_MAX)*T;
      tmp=cal(tx,ty); db delt=tmp-lst;
      if(delt<0||exp(delt/T)*RAND_MAX<rand())x=tx,y=ty,lst=tmp;
      if(tmp<ans)ansx=tx,ansy=ty,ans=tmp;
      T*=dt;
    }
}
int main()
{
  n=rd(); int sx=0,sy=0;
  for(int i=1;i<=n;i++)xx[i]=rd(),yy[i]=rd(),sx+=xx[i],sy+=yy[i];
  ansx=1.0*sx/n; ansy=1.0*sy/n; ans=cal(ansx,ansy);
  SA(); SA(); SA();
  printf("%.0lf\n",ans);
  return 0;
}

 

poj 2420 A Star not a Tree? —— 模拟退火

原文:https://www.cnblogs.com/Zinn/p/9876858.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!