现在的位置: 首页 > 综合 > 正文

[Poj2420]A Star not a Tree? (爬山算法||模拟退火算法)

2018年04月25日 ⁄ 综合 ⁄ 共 862字 ⁄ 字号 评论关闭
#include<iostream>
#include<cstdio>
#include<cmath>
#define inf 0x7fffffff
using namespace std;
inline int read(){
    int x=0,f=1;char ch=getchar();
    while(ch<'0'||ch>'9'){if(ch=='-')f=-1;ch=getchar();}
    while(ch>='0'&&ch<='9'){x=x*10+ch-'0';ch=getchar();}
    return x*f;
}
struct point{
	double x,y;
}p[101];
int n;
double xx,yy,ans,t;
inline double dis(double x,double y,point p){
	return sqrt((p.x-x)*(p.x-x)+(p.y-y)*(p.y-y));
}
inline double getsum(double x,double y){
	double res=0;
	for(int i=1;i<=n;i++)
		res+=dis(x,y,p[i]);
	return res;
}
int main(){
	while(scanf("%d",&n)!=EOF){
		xx=yy=0;t=10000;
		for(int i=1;i<=n;i++){
			scanf("%lf%lf",&p[i].x,&p[i].y);
			xx+=p[i].x;yy+=p[i].y;
		}
		xx/=n;yy/=n;
		ans=getsum(xx,yy);
		double x,y,tmp;
		while(t>0.02){
			x=y=0;
			for(int i=1;i<=n;i++){
				x+=(p[i].x-xx)/dis(xx,yy,p[i]);
				y+=(p[i].y-yy)/dis(xx,yy,p[i]);
			}
			tmp=getsum(xx+x*t,yy+y*t);
			if(tmp<ans){ans=tmp;xx+=x*t;yy+=y*t;}
			t*=0.9;
		}
		printf("%.0lf\n",ans);
	}
	return 0;
}

抱歉!评论已关闭.