题目链接:http://poj.org/problem?id=1379
这道题目应该算是真正意义上的模拟退火了,每一步基本上都是随机的
防止一个不准确,来30个,防止一个方向不行,随机来30个方向,取结果
最好的一个方向!
#include <string.h>
#include <stdio.h>
#include <algorithm>
#include <iostream>
#include <ctime>
#include <stdlib.h>
#include <cmath>
#define maxn 1010
#define MIN(a,b) (a<b?a:b)
#define MAX(a,b) (a>b?a:b)
#define inf 1e12
#define eps 1e-8
const double PI=acos(-1.0);
using namespace std;
struct point{
double x,y;
}po[maxn],ans_po[100];
int X,Y,n;
double ans[100];
double dis(point &a,point &b){
return sqrt((a.x-b.x)*(a.x-b.x)+(a.y-b.y)*(a.y-b.y));
}
double find_max(point &a){
double ans=inf,t;
for(int i=0;i<n;i++){
t=dis(a,po[i]);
ans=MIN(t,ans);
}
return ans;
}
int main(){
int i,j,k,t;
scanf("%d",&t);
double step,theta,now;
point temp;
srand(unsigned(time(NULL)));
while(t--){
scanf("%d%d%d",&X,&Y,&n);
for(i=0;i<n;i++)
scanf("%lf%lf",&po[i].x,&po[i].y);
for(i=0;i<30;i++){
ans_po[i].x=(rand()%1001)/1000.0*X;
ans_po[i].y=(rand()%1001)/1000.0*Y;
ans[i]=find_max(ans_po[i]);
}
step=MAX(X,Y);
while(step>eps){
for(i=0;i<30;i++){
theta=(rand()%1001)/500.00*PI;
for(j=0;j<30;j++){
temp.x=ans_po[j].x+cos(theta)*step;
temp.y=ans_po[j].y+sin(theta)*step;
if(temp.x>X || temp.x<0 || temp.y>Y || temp.y<0)
continue;
now=find_max(temp);
if(now>ans[j])ans[j]=now,ans_po[j]=temp;
}
}
step*=0.8;
}
j=0,now=ans[0];
for(i=1;i<30;i++)
if(ans[i]>now) now=ans[i],j=i;
printf("The safest point is (%.1lf, %.1lf).\n",ans_po[j].x,ans_po[j].y);
}
return 0;
}