如:求最小权值
各变量含义
- T:当前温度
- T_min:熄火时刻
- r:退火速度
- delta:距离差
- now:当前状态
- next:随机选的状态
- calc(now):当前状态权值
- res:当前最优解
- cnt:执行模拟退火次数
import random
import math
n = int(input())
now = list(range(0, n)) # 初始化状态
res = float('inf')
cnt = 50
def calc(st):
res = 0
# 计算状态st权值
return res
def SA():
T, T_min, r = 1e6, 1e-5, 0.97
while T > T_min:
x, y = random.randint(0, n), random.randint(0, n)
next = now[:]
next[x], next[y] = next[y], next[x] # 随机交换两个位置元素
a, b = calc(now), calc(next)
delta = b - a
if delta < 0: # 如果状态b的权值更小,则一定跳到这个状态
now = next[:]
else: # 否则以一定概率跳到比它权值高的状态
if math.exp(-delta / T) > random.random(): # 当x<0时,0<e的x次方<1,所以在0~1内找一个随机数与之比较
now = next[:]
res = min(res, calc(now)) # 尝试更新答案
T *= r
for _ in range(cnt):
SA()
print(res)