1. 程式人生 > 其它 >A Star not a Tree?

A Star not a Tree?

 

 

檢視程式碼

#include <cstdio>
#include <iostream>
#include <cstdlib>
#include <cstring>
#include <algorithm>
#include <cmath>
#define db double
#define inf 1e15
#define eps 1e-15
using namespace std;
int n;
db ax,ay,ans=inf,best=inf; 
db down=0.98,T0=3000;
struct point{
	db x,y;
}s[105];
db dist(point A,point B){
	return sqrt((A.x-B.x)*(A.x-B.x)+(A.y-B.y)*(A.y-B.y)); 
}
db getv(point x){
	db sum=0;	
	for(int i=1;i<=n;i++)sum+=dist(x,s[i]);
	return sum;
}
void solve(){
	for(db t=T0;t>eps;t*=down){
       db nx=ax+(rand()*2-RAND_MAX)*t;
       db ny=ay+(rand()*2-RAND_MAX)*t;
       db v=getv((point){nx,ny});
       db de=v-ans;
       if (de<0 || exp(-de/t)*RAND_MAX>rand()){
    		ax=nx;ay=ny;
    		ans=v;
       } 
       best=min(best,ans);
  }
}
int main(){
	scanf("%d",&n);
	for(int i=1;i<=n;i++){
		scanf("%lf%lf",&s[i].x,&s[i].y);		
		ax+=s[i].x,ay+=s[i].y;
	}
	ax/=n;ay/=n;
	ans=getv((point){ax,ay});
	for(int i=1;i<=100;i++)solve();
	printf("%d\n",(int)(best+0.5));
	return 0;
}

模擬退火好題

模擬退火:一種隨機化演算法

一開始有一個溫度T0,溫度會乘以下降係數down