题目大意:
给定n个点,求一点到所有点距离的最小值。
解题思路:
模拟退火真是神,
一般的爬山算法就是先设置一个起始点较大的步长step(初始温度),每次随机向一个方向走step,若该点更优,则更新答案,并转移起始点位置。操作完后减小等比例减小step重复上述操作若干次(尽量多),则可得到近似最优解。即:每次都往更优的地方走。
而模拟退火只是在爬山算法的基础上有一定概率往劣处走。
#include<cstdio>
#include<algorithm>
#include<cmath>
using namespace std;
int read()
{
int i=0,f=1;char c;
for(c=getchar();(c<'0'||c>'9')&&c!='-';c=getchar());
if(c=='-')f=-1,c=getchar();
for(;c>='0'&&c<='9';c=getchar())i=(i<<3)+(i<<1)+c-'0';
return i*f;
}
const int N=105;
struct point
{
double x,y;
point(){}
point(double _x,double _y):x(_x),y(_y){}
inline friend point operator - (const point &a,const point &b)
{return point(a.x-b.x,a.y-b.y);}
inline double dis(){return sqrt(x*x+y*y);}
}p[N];
int n;
double calc(point a)
{
double res=0;
for(int i=1;i<=n;i++)res+=(p[i]-a).dis();
return res;
}
int main()
{
//freopen("lx.in","r",stdin);
n=read();
for(int i=1;i<=n;i++)p[i].x=read(),p[i].y=read();
double ans=1e20,step=10000;point s=p[1];
while(step>1e-10)
{
double ang=rand()%314;
point t=point(s.x+step*cos(ang),s.y+step*sin(ang));
double D=calc(t);
if(D<ans)s=t,ans=D;
else
{
if(exp((D-ans)/step)<(rand()%10000)/10000.0)
ans=D,s=t;
}
step*=0.99;
}
printf("%.0f",ans);
return 0;
}