版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/leekerian/article/details/82263457
第一道模拟退火
#include <iostream>
#include <cmath>
#include <cstdio>
#include <algorithm>
using namespace std;
const int maxn=111;
struct Point
{
double x,y;
Point(){}
Point(double _x,double _y)
{
x=_x;
y=_y;
}
Point operator -(const Point &b)const
{
return Point(x-b.x,y-b.y);
}
double operator ^(const Point &b)const
{
return x*b.y-y*b.x;
}
double operator *(const Point &b)const
{
return x*b.x+y*b.y;
}
};
Point p[maxn];
int mx[4]={0,0,1,-1};
int my[4]={1,-1,0,0};
const double eps=1e-8;//终点温度
double T=100;//启示温度
const double delta=0.98;//温度下降梯度
int sgn(double x)
{
if(fabs(x)<eps)
return 0;
if(x<0)
return -1;
else
return 1;
}
double dist(Point a,Point b)
{
return sqrt((a-b)*(a-b));
}
double get_ans(int n,Point s)
{
double ans=0;
for(int i=0;i<n;i++)
ans+=dist(p[i],s);
return ans;
}
double search_(int n)
{
Point s=p[0];//qidian
double ans=1e99;
while(T>eps)
{
bool flag=1;
while(flag)
{
flag=0;
for(int i=0;i<4;i++)
{
Point t;
t=s;
t.x=t.x+mx[i]*T;
t.y=t.y+my[i]*T;
double ans1=get_ans(n,t);
if(ans1<ans)
{
s=t;
flag=1;
ans=ans1;
}
}
}
T=T*delta;
}
return ans;
}
int main()
{
int n;
while(scanf("%d",&n)!=EOF)
{
for(int i=0;i<n;i++)
scanf("%lf %lf",&p[i].x,&p[i].y);
printf("%.0lf\n",search_(n));
}
return 0;
}