[LeetCode] 服务中心的最佳位置 模拟退火(Python语言实现)

题目链接:服务中心的最佳位置

题面:

代码:

import math
import random

class Solution:
    def getMinDistSum(self, positions):
        # 温度变化率
        K = 0.97
        # 结束温度,控制降温时间
        EPS = 1E-15
        # 计算自变量的增量
        def get(T):
            return T * random.randint(-32767, 32767)

        def calc(positions, nowx, nowy):
            ans = 0
            for x,y in positions:
                ans += (abs(nowx - x) ** 2 + abs(nowy - y) ** 2) ** 0.5
            return ans
        x0,y0=0,0
        for x,y in positions:
            x0+=x
            y0+=y
        x0/=len(positions)
        y0/=len(positions)
        ans = calc(positions, x0, y0)
        cnt = 2
        while cnt > 0:
            cnt -= 1
            cur = ans
            x1, y1 = x0, y0
            T = 100000
            # 初始温度
            while T > EPS:
                x2, y2 = x1 + get(T), y1 + get(T)
                temp = calc(positions, x2, y2)
                if temp < ans:
                    ans = temp
                    x0, y0 = x2, y2
                if cur > temp or math.exp((cur - temp) / T) > random.random():
                    cur = temp
                    x1, y1 = x2, y2
                T *= K
        return ans

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值