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

时间:2023-03-09 07:55:08
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=;
int n,xx[xn],yy[xn];
db ansx,ansy,ans;
int rd()
{
int ret=,f=; char ch=getchar();
while(ch<''||ch>''){if(ch=='')f=; ch=getchar();}
while(ch>=''&&ch<='')ret=(ret<<)+(ret<<)+ch-'',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=;
for(int i=;i<=n;i++)ret+=dist(x,y,xx[i],yy[i]);
return ret;
}
void SA()
{
db T=,x=ansx,y=ansy,lst=ans,tx,ty,tmp;
while(T>eps)
{
tx=x+(rand()*-RAND_MAX)*T;
ty=y+(rand()*-RAND_MAX)*T;
tmp=cal(tx,ty); db delt=tmp-lst;
if(delt<||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=,sy=;
for(int i=;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 ;
}