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

 

posted @ 2022-03-15 10:51  liankewei123456  阅读(17)  评论(0编辑  收藏  举报