害怕爬山算法挂掉,所以改成了新的模拟退火
模拟退火就是在爬山算法的基础上又新增加了一个 以一定概率接受最优解。
就是一个exp 比一个随机在(0,1)的概率小,就接受。
#include<cstdio>
#include<iostream>
#include<cstring>
#include<cstdlib>
#include<algorithm>
#include<queue>
#include<cmath>
#include<ctime>
using namespace std;
const int maxn=105;
int n;
double xi[maxn],yi[maxn];
double dis(double x,double y)
{
double res=0;
for(int i=1;i<=n;i++)
{
res+=sqrt((xi[i]-x)*(xi[i]-x)+(yi[i]-y)*(yi[i]-y));
}
return res;
}
int main()
{
srand(time(NULL));
while(scanf("%d",&n)!=EOF)
{
for(int i=1;i<=n;i++)scanf("%lf%lf",&xi[i],&yi[i]);
double step=100000;
double x=xi[1],y=yi[1];
double ans=dis(x,y);
while(step>1e-10)
{
double rad=rand()%360+1;
double nx=x+step*cos(rad);
double ny=y+step*sin(rad);
double tmp=dis(nx,ny);
if(tmp<ans)
{
ans=tmp;
x=nx;
y=ny;
}
else
{
if(exp((tmp-ans)/step)<(rand()%10000)/10000.0)
{
ans=tmp;
x=nx;
y=ny;
}
}
step*=0.99;
}
printf("%.0f\n",ans);
}
return 0;
}