如何在 Python 中为 TSP 实现动态编程算法?

Pav*_*vel 5 python algorithm dynamic-programming traveling-salesman

我想在 Python 中使用动态编程算法解决 TSP 问题。问题是:

  • 输入:表示为点列表的城市。例如,[(1,2), (0.3, 4.5), (9, 3)...]。城市之间的距离定义为欧几里得距离。
  • 输出:此实例的旅行推销员旅行的最低成本,四舍五入到最接近的整数。

伪代码是:

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.
Run Code Online (Sandbox Code Playgroud)

我的困惑是:

如何使用子集索引列表,也就是如何有效地实现伪代码中的第 5 行。

小智 3

您可以将集合编码为整数:整数的第 i 位将代表第 i 个城市的状态(即我们是否将其纳入子集中)。
例如,35 10 = 100011 2将代表城市 {1, 2, 6}。这里我从最右边的位开始数,它代表城市 1。

为了使用子集的这种表示形式对列表进行索引,您应该创建长度为2 n的二维数组:

# Assuming n is given.
A = [[0 for i in xrange(n)] for j in xrange(2 ** n)]
Run Code Online (Sandbox Code Playgroud)

这是因为,使用 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.
Run Code Online (Sandbox Code Playgroud)

这就是我实现伪代码的方式(警告:未进行测试):

# 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))
Run Code Online (Sandbox Code Playgroud)

除了拥有实现伪代码所需的所有功能之外,这种方法将比元组\字典更快。