poj2420 A Star not a Tree? 爬山算法

       随机化算法第一发,参考了黄学长的代码。实际上就是每次向可能的最近点移动然后看是否更优,如果更优就移过去。然后不断缩短步长就可以了。虽然会受局部峰值影响但是这么写好像没有问题。。。

AC代码如下:

#include<iostream>
#include<cstdio>
#include<cmath>
#include<cstdlib>
#define eps 1e-3
using namespace std;

int n; double x[1005],y[1005];
double dist(double x1,double y1,double x2,double y2){
	return sqrt((x1-x2)*(x1-x2)+(y1-y2)*(y1-y2));
}
double solve(double u,double v){
	double sum=0; int i;
	for (i=1; i<=n; i++) sum+=dist(u,v,x[i],y[i]);
	return sum;
}
int main(){
	scanf("%d",&n); int i; double sx=0,sy=0;
	for (i=1; i<=n; i++){
		scanf("%lf%lf",&x[i],&y[i]);
		sx+=x[i]; sy+=y[i];
	}
	sx/=n; sy/=n; double ans=solve(sx,sy),t;
	for (t=1e4; t>eps; t*=0.9){
		double dx=0,dy=0,tmp;
		for (i=1; i<=n; i++){
			tmp=dist(sx,sy,x[i],y[i]);
			dx+=(x[i]-sx)/tmp; dy+=(y[i]-sy)/tmp;
		}
		tmp=solve(sx+dx,sy+dy);
		if (tmp<ans){
			ans=tmp; sx+=dx; sy+=dy;
		}
	}
	printf("%.0lf\n",ans);
	return 0;
}

by lych
2016.2.18

你可能感兴趣的:(爬山算法,随机化)