码迷,mamicode.com
首页 > 其他好文 > 详细

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

时间:2018-10-30 17:18:31      阅读:118      评论:0      收藏:0      [点我收藏+]

标签:font   rand   tchar   not   for   int   a star   sqrt   oid   

题目: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? —— 模拟退火

标签:font   rand   tchar   not   for   int   a star   sqrt   oid   

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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!