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

题目: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
",ans);
  return 0;
}
原文地址:https://www.cnblogs.com/Zinn/p/9876858.html