我想在Python中使用动态编程算法来解决TSP问题。问题是:
伪代码是:
Let A = 2-D array, indexed by subsets of {1, 2, ,3, ..., n} that contains 1 and destinations j belongs to {1, 2, 3,...n}
1. Base case:
2. if S = {0}, then A[S, 1] = 0;
3. else, A[S, 1] = Infinity.
4.for m = 2, 3, ..., n: // m = subproblem size
5. for each subset of {1, 2,...,n} of size m that contains 1:
6. for each j belongs to S and j != 1:
7. A[S, j] = the least value of A[S-{j},k]+the distance of k and j for every k belongs to S that doesn't equal to j
8.Return the least value of A[{1,2..n},j]+the distance between j and 1 for every j = 2, 3,...n.
我的困惑是:
如何使用子集索引列表,即如何有效地在伪代码中实现第5行。
答案 0 :(得分:2)
你可以将集合编码为整数:我的整数位将表示第i个城市的状态(即我们是否将其置于子集中)。
例如,35 10 = 100011 2 将代表城市{1,2,6}。在这里,我从最右边的位数,代表城市1。
为了使用子集的这种表示来索引列表,您应该创建长度 2 n 的2D数组:
# Assuming n is given.
A = [[0 for i in xrange(n)] for j in xrange(2 ** n)]
这是因为使用n位整数可以表示{1,2,...,n}的每个子集(请记住,每个位对应于一个城市)。
这种表现形式为您提供了许多不错的选择:
# Check whether some city (1-indexed) is inside subset.
if (1 << (i - 1)) & x:
print 'city %d is inside subset!' % i
# In particular, checking for city #1 is super-easy:
if x & 1:
print 'city 1 is inside subset!'
# Iterate over subsets with increasing cardinality:
subsets = range(1, 2 ** n)
for subset in sorted(subsets, key=lambda x: bin(x).count('1')):
print subset,
# For n=4 prints "1 2 4 8 3 5 6 9 10 12 7 11 13 14 15"
# Obtain a subset y, which is the same as x,
# except city #j (1-indexed) is removed:
y = x ^ (1 << (j - 1)) # Note that city #j must be inside x.
这是我实现你的伪代码的方法(警告:没有进行测试):
# INFINITY and n are defined somewhere above.
A = [[INFINITY for i in xrange(n)] for j in xrange(2 ** n)]
# Base case (I guess it should read "if S = {1}, then A[S, 1] = 0",
because otherwise S = {0} is not a valid index to A, according to line #1)
A[1][1] = 0
# Iterate over all subsets:
subsets = range(1, 2 ** n)
for subset in sorted(subsets, key=lambda x: bin(x).count('1')):
if not subset & 1:
# City #1 is not presented.
continue
for j in xrange(2, n + 1):
if not (1 << (j - 1)) & subset:
# City #j is not presented.
continue
for k in xrange(1, n + 1):
if k == j or not (1 << (k - 1)) & subset:
continue
A[subset][j] = min(A[subset][j], A[subset ^ (1 << (j - 1))][k] + get_dist(j, k))
除了具有实现伪代码所需的所有功能之外,这种方法比使用元组\ dicts更快。