首页 > 代码库 > 【POJ2420】A star not a tree?

【POJ2420】A star not a tree?

蒟蒻开始学模拟退火……

起初一直不肯学,因为毕竟玄学算法……

哎呀玄学怎么就没用呢?对不对?

#include<iostream>
#include<cstdio>
#include<algorithm>
#include<cstring>
#include<cstdlib>
#include<cmath>
#include<ctime>
using namespace std;
int n;
double xx,yy,ans,T;
struct Point{double x,y;}p[110];
inline double sqr(double x){return x*x;}
inline double dis(double x,double y,Point p){
    return sqrt(sqr(x-p.x)+sqr(y-p.y));
}
inline double getsum(double x,double y){
    double ret=0;
    for(int i=1;i<=n;i++)ret+=dis(x,y,p[i]);
    return ret;
}
int main(){
    srand(time(NULL));
    while(~scanf("%d",&n)){
        xx=yy=0;ans=1e20;T=100000;
        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 tmp,x,y;
        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;}
            else if(log((tmp-ans)/T)<(rand()%10000)/10000.0)
            {ans=tmp;xx+=x*T;yy+=y*T;}
            T*=0.9;
        }
        printf("%.0lf\n",ans);
    }
}

 

【POJ2420】A star not a tree?