simulate anneal

题目链接:Groundhog Build Home

double random(void)
{
    return (rand()%10000+1)/10000.0;
}

struct node
{
    double x,y;
} a[1005];

int n;

double getmax(double x,double y)
{
    double maxx=0.0;
    for(int i=1; i<=n; i++)
    {
        double res=sqrt((x-a[i].x)*(x-a[i].x)+(y-a[i].y)*(y-a[i].y));
        if(res>maxx)maxx=res;
    }
    return maxx;
}

int main()
{
    srand(time(0));
    double max_x,max_y;
    while(~scanf("%lf%lf%d",&max_x,&max_y,&n))
    {
        memset(a,0,sizeof(a));
        for(int i=1; i<=n; i++)
            scanf("%lf%lf",&a[i].x,&a[i].y);
        double x=random()*max_x,y=random()*max_y;
        double step=sqrt(max_x*max_x+max_y*max_y)/2.0;
        double ans_x=x,ans_y=y,minn=1e18,t=50;
        double last_res=getmax(x,y);
        while(step>eps)
        {
            double nexx=x+cos(random()*2*pi)*step;
            double nexy=y+sin(random()*2*pi)*step;
            if(nexx<0 || nexx>max_x)continue;
            if(nexy<0 || nexy>max_y)continue;
            double now_res=getmax(nexx,nexy);
            double res=now_res-last_res;
            if(res<=0)
            {
                ans_x=x=nexx,ans_y=y=nexy;
                minn=last_res=now_res;
            }
            else if(exp(-res/t)>random())
            {
                x=nexx,y=nexy;
                last_res=now_res;
            }
            step*=0.9999,t*=0.97;
        }
        printf("(%.1lf,%.1lf).\n%.1lf\n",ans_x,ans_y,minn);
    }
    return 0;
}

你可能感兴趣的:(simulate anneal)