旅行商问题的动态规划解法
一个售货员必须访问n个城市,这n个城市是一个完全图,售货员需要恰好访问所有城市的一次,并且回到最终的城市。
城市与城市之间有一个旅行费用,售货员希望旅行费用之和最少。
旅行商问题是np问题,一般可以使用回溯法或者动态规划解决。
class Solution:
def __init__(self, X, start_node):
self.X = X
self.start_node = start_node
self.array = [[0] * (2 ** (len(self.X) - 1)) for i in range(len(self.X))]
def transfer(self, sets):
su = 0
for s in sets:
su = su + 2 ** (s - 1)
return su
def tsp(self):
s = self.start_node
num = len(self.X)
cities = list(range(num))
cities.pop(cities.index(s))
node = s
return self.solve(node, cities)
def solve(self, node, future_sets):
if len(future_sets) == 0:
return self.X[node][self.start_node]
d = 9999999
distance = []
for i in range(len(future_sets)):
s_i = future_sets[i]
copy = future_sets[:]
copy.pop(i)
distance.append(self.X[node][s_i] + self.solve(s_i, copy))
d = min(distance)
next_one = future_sets[distance.index(d)]
c = self.transfer(future_sets)
self.array[node][c] = next_one
return d
n = int(input())
m = int(input())
D = [[9999999 for j in range(n)] for i in range(n)]
for i in range(m):
a, b, t = list(map(float, input().split()))
a,b = int(a),int(b)
D[a][b] = t
D[b][a] = t
S = Solution(D, 0)
res = int(S.tsp())
if res >= 9999999:
print(-1)
else:
print(res)