hdu 3932 Groundhog Build Home——模拟退火

时间:2023-12-22 12:20:26

题目:http://acm.hdu.edu.cn/showproblem.php?pid=3932

注意平均值与最远的点距离为0的情况。所以初值设成-1,这样 id 就不会乱。不过设成0也可以。注意判断 pr==0 ,因为有除法。

#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<ctime>
#include<cmath>
#include<cstdlib>
#define db double
using namespace std;
const int N=;
const db dc=0.99,eps=1e-,INF=2e4;
int n,nx[N],ny[N],pid;
db ans,px,py;
int rdn()
{
int ret=;bool fx=;char ch=getchar();
while(ch>''||ch<''){if(ch=='-')fx=;ch=getchar();}
while(ch>=''&&ch<='') ret=(ret<<)+(ret<<)+ch-'',ch=getchar();
return fx?ret:-ret;
}
db dis(db x0,db y0,db x1,db y1)
{
return sqrt((x0-x1)*(x0-x1)+(y0-y1)*(y0-y1));
}
void SA(db T)
{
db x0=px,y0=py,pr=ans;int id=pid;
while(T>eps)
{
pr=;
for(int i=;i<=n;i++)
{
db tmp=dis(x0,y0,nx[i],ny[i]);
if(tmp>pr)pr=tmp,id=i;
}
if(pr<ans)ans=pr,pid=id,px=x0,py=y0;
if(!pr)return;
x0=x0+(nx[id]-x0)/pr*T; y0=y0+(ny[id]-y0)/pr*T;
T*=dc;
}
}
int main()
{
srand(time());
int tx,ty;
while(scanf("%d%d%d",&tx,&ty,&n)==)
{
for(int i=;i<=n;i++)nx[i]=rdn(),ny[i]=rdn(),px+=nx[i],py+=ny[i];
px/=n; py/=n; ans=INF;
SA();SA();
printf("(%.1lf,%.1lf).\n%.1lf\n",px,py,ans);
}
return ;
}