POJ 2420 A Star not a Tree? (费马点 爬山算法/模拟退火)

http://poj.org/problem?id=2420
题意:求离给定 n n n个点距离和最小的点(费马点)到这 n n n个点的距离和。

学习一下传说中的爬山算法和模拟退火算法。

//爬山算法
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <iostream>
#include <cmath>
using namespace std;
const double PI=acos(-1.0);
const int MAXN=110;
double dx[4]={1,-1,0,0},dy[4]={0,0,1,-1};
int n;
struct Point
{
	double x,y;
	Point(){}
	Point(double _x,double _y)
	{
		x=_x;y=_y;
	}
	Point operator -(const Point &b)const
	{
		return Point(x-b.x,y-b.y);
	}
	double operator ^(const Point &b)const
	{
		return x*b.y-y*b.x;
	}
	double operator *(const Point &b) const
	{
		return x*b.x+y*b.y;
	}
	void input()
	{
		scanf("%lf%lf",&x,&y);
	}
};
Point p[MAXN];
//距离的平方
double dist(Point a,Point b)
{
	return sqrt((a-b)*(a-b));
}
double calc(Point t)
{
    double res=0;
    for(int i=0;i<n;i++)
        res+=dist(p[i],t);
    return res;
}
int round_double(double number)
{
    return (number>0.0)?(number+0.5):(number-0.5);
}
double sx,sy;
int main()
{
    scanf("%d",&n);
    for(int i=0;i<n;i++)
    {
        p[i].input();
        sx+=p[i].x;sy+=p[i].y;
    }
    sx/=n;sy/=n;
    double ans=calc(Point(sx,sy));
    for(double i=1e4;i>1e-3;i*=0.9)
    {
        for(int j=0;j<4;j++)
        {
            double tx=sx+dx[j]*i,ty=sy+dy[j]*i;
            double tmp=calc(Point(tx,ty));
            if(tmp<ans)
            {
                ans=tmp;
                sx=tx;sy=ty;
            }
        }
    }
    printf("%d",round_double(ans));
    return 0;
}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值