【题解】洛谷P1337[JSOI2004]平衡点/吊打XXX 模拟退火

题目链接
【题解】洛谷P1337[JSOI2004]平衡点/吊打XXX 模拟退火
【题解】洛谷P1337[JSOI2004]平衡点/吊打XXX 模拟退火


跟着大佬博客学模拟退火,顺带把这题做()了。

#include<cstdio>
#include<cstdlib>
#include<ctime>
#include<cmath>
const int N=1e3+10;
int n;
const double MAX_TIME=0.777;
double ans=1e18,ansx,ansy;
struct node{
	int x,y,w;
}a[N];
double calc(double x,double y)
{
	double now=0;
	for(int i=1;i<=n;i++)
	{
		double nx=x-a[i].x,ny=y-a[i].y;
		now+=sqrt(nx*nx+ny*ny)*a[i].w;
	}
	return now;
}
void SA()
{
	double t=2000,x=ansx,y=ansy;
	while(t>1e-14)
	{
		double nx=x+(rand()*2-RAND_MAX)*t;
		double ny=y+(rand()*2-RAND_MAX)*t;
		double now=calc(nx,ny);
		if(now<ans)
		    x=nx,y=ny,ansx=nx,ansy=ny,ans=now;
		else if(exp((ans-now)/t)*RAND_MAX>rand())x=nx,y=ny;
		t*=0.996;
	}
}
int main()
{
	//freopen("in.txt","r",stdin);
    srand((unsigned)time(0));
    scanf("%d",&n);
    for(int i=1;i<=n;i++)
        scanf("%d%d%d",&a[i].x,&a[i].y,&a[i].w),ansx+=a[i].x,ansy+=a[i].y;
    ansx/=n;ansy/=n;
    while ((double)clock()/CLOCKS_PER_SEC<MAX_TIME) SA();
    printf("%.3f %.3f\n",ansx,ansy);
    return 0;
}

总结

模拟退火入门