题意:https://blog.csdn.net/Haipai1998/article/details/81566458 到一个矩形中N个点的最大值,最小
#include<bits/stdc++.h>
#define N 1003
using namespace std;
const double eps=1e-10;
const double dd=0.88,PI=acos(-1.0);
double X,Y;
int n;
struct Point
{ //点的定义
double x, y;
Point(){
}
Point(double x, double y) : x(x), y(y) {}
}p[N];
int sign(double x)
{
return fabs(x)<x?0:x<0?-1:1;
}
double length(Point a,Point b)
{
return sqrt( (a.x-b.x)*(a.x-b.x)+(a.y-b.y)*(a.y-b.y) );
}
double cul(Point t)
{
double ans=1e20;
for(int i=0;i<n;i++)
{
ans=min(ans,length(t,p[i]));
}
return ans;
}
double myrand()
{
return rand()%10000/10000.0; ///rand_MAX=2^15-1;
}
void SA(Point &ans)
{
double T=sqrt(X*X+Y*Y)/2;///步长是半对角线
double E=cul(ans);///最初的最大值
while(T>eps)
{/// 循环条件大于eps
Point next;
double mmax=0.0; ///保存100个点中最小距离最大的点
for(int i=0;i<100;++i)
{/// 随机100个点去扩展
double x,y;
double ang=myrand()*2*PI;///随机一个角度
x=ans.x+cos(ang)*T;
y=ans.y+sin(ang)*T;
if(sign(x)<0) x=0.0;///不超过矩阵范围
if(sign(x-X)>0) x=X;
if(sign(y)<0) y=0.0;
if(sign(y-Y)>0) y=Y;
Point t=Point(x,y);
double nE=cul(t);
if(sign(nE-mmax)>=0)
{
next=t;
mmax=nE;
}
}
if(sign(mmax-E)>0 || exp((mmax-E)/T>myrand()))
{ /// 如果比当前值要大 或者 比当前值小,但是满足放弃当前局部最优解的条件.exp中的函数一定要满足和T成反比例
E=mmax;
ans=next;
}
T*=dd;/// 乘的数越大,循环次数越多,理论上越逼近全局最优解,但时间会剧增,
}
}
int main()
{
//freopen("t.txt","r",stdin);
srand(time(0));
int T;
scanf("%d",&T);
while(T--)
{
scanf("%lf%lf%d",&X,&Y,&n);
for(int i=0;i<n;i++)
{
double x,y;
scanf("%lf%lf",&x,&y);
p[i].x=x,p[i].y=y;
}
Point ans=Point(X/2,Y/2);///把矩阵中心当作是最初答案
SA(ans);///SA是模拟退火的英文简称
/*SA(ans);
SA(ans);*/
printf("The safest point is (%.1f, %.1f).\n",ans.x,ans.y);
}
return 0;
}