poj 2420 A Star not a Tree?(贪心+求多边形费马点)

15 篇文章 0 订阅
5 篇文章 0 订阅

【题目大意】:找出一个点,使得到多边形每个点的距离和最小。输出最小距离和。


【解题思路】:求的是一个多边形的费马点。三边以上没有公式,我们可以使用随机化变步长贪心法来解这道题。


【随机化变步长贪心法】:随机选取一个点,再取一个步长,朝这个方向走,如果新位置到各点距离比原来小,则走过去。直到走不动为止,再缩小步长。直到步长小于题目精度。


【代码】:

#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <vector>
#include <queue>
#include <cmath>
#include <string>
#include <cctype>
#include <map>
#include <iomanip>
                   
using namespace std;
                   
#define eps 1e-8
#define pi acos(-1.0)
#define inf 1<<30
#define linf 1LL<<60
#define pb push_back
#define lc(x) (x << 1)
#define rc(x) (x << 1 | 1)
#define lowbit(x) (x & (-x))
#define ll long long

struct Point{
    double x,y;
    Point(){}
    Point(double a,double b){
        x=a,y=b;
    }
}point[101];

double pt_distance(const Point &p1,const Point &p2){
    return sqrt((p1.x-p2.x)*(p1.x-p2.x)+(p1.y-p2.y)*(p1.y-p2.y));
}

double get_all_dis(const Point &p,int n){
    double ans=0.0;
    for (int i=0; i<n; i++) ans+=pt_distance(point[i],p);
    return ans;
}

int main() {
    int n;
    while (~scanf("%d",&n)){
        for (int i=0; i<n; i++)
            scanf("%lf%lf",&point[i].x,&point[i].y);
        Point st=point[0];
        double step=100,mind=get_all_dis(st,n);
        while (step>0.2){
            int ok=1;
            while (ok){
                Point tmp,nt;
                double t;
                ok=0,nt=st;
                tmp=Point(st.x,st.y+step);
                t=get_all_dis(tmp,n);
                if (t<mind) mind=t,ok=1,nt=tmp;
            
                tmp=Point(st.x,st.y-step);
                t=get_all_dis(tmp,n);
                if (t<mind) mind=t,ok=1,nt=tmp;
            
                tmp=Point(st.x+step,st.y);
                t=get_all_dis(tmp,n);
                if (t<mind) mind=t,ok=1,nt=tmp;
            
                tmp=Point(st.x-step,st.y);
                t=get_all_dis(tmp,n);
                if (t<mind) mind=t,ok=1,nt=tmp;

                st=nt;
            }
            step=step/2.0;
        }
        int ans=(int)(mind+0.5)*100/100;
        printf("%d\n",ans);
    }
    return 0;
}



  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值