您的位置:首页 > 其它

POJ - 2420 A Star not a Tree?

2017-08-11 13:41 239 查看
题目:给你平面上n个点,让你找一点,使得这个点到这n个点的距离之后最小,输出最小的距离之和

思路:模拟退火

代码:

#pragma comment(linker, "/STACK:1024000000,1024000000")
#include<iostream>
#include<algorithm>
#include<cstdio>
#include<cmath>
#include<cstring>
#include<string>
#include<vector>
#include<map>
#include<set>
#include<queue>
#include<stack>
#include<list>
#include<numeric>
using namespace std;
#define LL long long
#define ULL unsigned long long
#define INF 0x3f3f3f3f
#define mm(a,b) memset(a,b,sizeof(a))
#define PP puts("*********************");
template<class T> T f_abs(T a){ return a > 0 ? a : -a; }
template<class T> T gcd(T a, T b){ return b ? gcd(b, a%b) : a; }
template<class T> T lcm(T a,T b){return a/gcd(a,b)*b;}
// 0x3f3f3f3f3f3f3f3f
// 0x3f3f3f3f

#define T_min 1e-10//搜索停止阈值
#define delta 0.98//温度下降速度
const int maxn=105;
struct Node{
double x,y;
}p[maxn];
int n;
double Dis(double x,double y){
double res=0;
for(int i=0;i<n;i++){
res+=sqrt((x-p[i].x)*(x-p[i].x)+(y-p[i].y)*(y-p[i].y));
}
return res;
}
double Search(){
double x=p[0].x,y=p[0].y;//随机初始化一个点开始搜索
double T=100000;//初始化温度
double ans=Dis(x,y);//初始化答案
while(T>T_min){
double rad=rand()%360+1;
double nx=x+T*cos(rad);
double ny=y+T*sin(rad);
double cur=Dis(nx,ny);
if(cur<ans){
ans=cur;
x=nx;
y=ny;
}
else if(exp((cur-ans)/T)<rand()/(RAND_MAX+1.0)){
ans=cur;
x=nx;
y=ny;
}
T=T*delta;
}
return ans;
}
int main(){

while(~scanf("%d",&n)){
for(int i=0;i<n;i++)
scanf("%lf%lf",&p[i].x,&p[i].y);
double ans=Search();
printf("%.0f\n",ans);
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: