码迷,mamicode.com
首页 > 其他好文 > 详细

LC 1515. Best Position for a Service Centre (Simulated Annealing)

时间:2020-07-12 19:05:29      阅读:75      评论:0      收藏:0      [点我收藏+]

标签:size   int   loading   cpp   sqrt   src   lin   while   sts   

link
技术图片

class Solution {
public:
    int n;
    double eps=1E-6;
    const int dx[4]={-1,0,1,0};
    const int dy[4]={0,1,0,-1};
    double getMinDistSum(vector<vector<int>>& positions) {
        n=positions.size();
        double xavg=0.0;
        double yavg=0.0;
        for(auto& p:positions){
            xavg+=p[0];
            yavg+=p[1];
        }
        xavg/=n;
        yavg/=n;
        double mindis=dist(xavg,yavg,positions);
        double step=100.0;
        int done=0;
        while(step>eps){
            done=0;
            for(int i=0;i<4;i++){
                double nx=xavg+step*dx[i];
                double ny=yavg+step*dy[i];
                
                double t=dist(nx,ny,positions);
                if(t<mindis){
                    mindis=t;
                    xavg=nx;
                    yavg=ny;
                    done=1;
                    break;
                }
            }
            if(!done){
                step/=2;
            }
        }
        return mindis;
    }
    
    double dist(double x, double y,vector<vector<int>>& positions){
        double ret=0.0;
        for(int i=0;i<n;i++){
            double dx=positions[i][0]-x;
            double dy=positions[i][1]-y;
            ret+=sqrt(dx*dx+dy*dy);
        }
        return ret;
    }
};

LC 1515. Best Position for a Service Centre (Simulated Annealing)

标签:size   int   loading   cpp   sqrt   src   lin   while   sts   

原文地址:https://www.cnblogs.com/FEIIEF/p/13289110.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!