最近再刷模拟退火,发现这是一个nb的算法。
刚开始只能最一些简单的题。
题目:求到所有点距离和的最小值,随机化步长。
代码:
#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<cmath>
using namespace std;
#define NUM 30
#define R 10000
#define pi acos(-1.0)
const int N = 100+10;
int n;
struct point
{
double x;double y;
double dis;
point() {}
point(double xx,double yy):x(xx),y(yy){}
}p[N],pp[N];
double dist(point a,point b)
{
return sqrt((a.x-b.x)*(a.x-b.x)+(a.y-b.y)*(a.y-b.y));
}
double getDis(point a)
{
double ans = 0;
for(int i=1;i<=n;i++)
ans+=dist(a,p[i]);
return ans;
}
void init()
{
for(int i=1;i<=NUM;i++)
{
int tx = rand()%R;
int ty = rand()%R;
pp[i].x = tx;
pp[i].y = ty;
pp[i].dis = getDis(pp[i]);
}
}
int isIn(double x,double y)
{
if(x<0 || x>R ||y<0 ||y>R)
return 0;
return 1;
}
int main()
{
cin>>n;
for(int i=1;i<=n;i++)
scanf("%lf%lf",&p[i].x,&p[i].y);
init();
double T = 1e5;
double Tmin = 1e-3;
double r = 0.9;
while(T > Tmin)
{
for(int i=1;i<=NUM;i++)
{
double x = pp[i].x , y = pp[i].y;
for(int j=1;j<=20;j++)
{
double angle = (rand()%1000)*1.0/1000*2.0*pi;
double tx = x + T*cos(angle);
double ty = y + T*sin(angle);
if(!isIn(tx,ty)) continue;
point tmp(tx,ty);
double dis = getDis(tmp);
tmp.dis = dis;
if(dis < pp[i].dis)
pp[i] = tmp;
}
}
T*=r;
}
double ans = 1e10;
for(int i=1;i<=NUM;i++)
ans = min(ans,pp[i].dis);
printf("%d\n",(int)(ans+0.5));
return 0;
}