【问题标题】:dynamic programming pseudocode for Travelling Salesman旅行推销员的动态规划伪代码
【发布时间】:2010-02-16 12:54:43
【问题描述】:

这是 TSP(旅行商问题)的动态编程伪代码。我了解它的最佳子结构,但我不知道红括号中的代码是做什么的。

我不是要求任何人编写实际代码,我只需要解释正在发生的事情,以便我可以编写自己的......谢谢:)

这里是伪代码的链接,我不能在这里上传。 http://www.imagechicken.com/viewpic.php?p=1266328410025325200&x=jpg

【问题讨论】:

    标签: functional-programming dynamic-programming


    【解决方案1】:

    这里是一些不太数学的伪代码。我不知道这是否会解释正在发生的事情,但它可能会帮助您阅读它。这不是函数式算法(到处都是:=),所以我将使用 Python 伪代码。

    # I have no idea where 'i' comes from. It's not defined anywhere
    for k in range(2,n):
        C[set(i,k), k] = d(1,k)
    shortest_path = VERY_LARGE_NUMBER
    # I have to assume that n is the number of nodes in the graph G
    # other things that are not defined:
    # d_i,j -- I will assume it's the distance from i to j in G
    for subset_size in range(3,n):
        for index_subset in subsets_of_size(subset_size, range(1,n)):
            for k in index_subset:
                C[S,k] = argmin(lambda m: C[S-k,m] + d(G,m,k), S - k)
                shortest_path = argmin(lambda k: C[set(range(1,n)),k] + d(G,1,k), range(2,n))
    return shortest_path
    
    # also needed....
    def d(G, i, j):
        return G[i][j]
    def subsets_of_size(n, s): # returns a list of sets
        # complicated code goes here
        pass
    def argmin(f, l):
        best = l[0]
        bestVal = f(best)
        for x in l[1:]:
            newVal = f(x)
            if newVal < bestVal:
                best = x
                bestVal = newVal
        return best
    

    一些注意事项:

    1. 源算法不完整。至少,它的格式在内部循环中很奇怪,并且它在第二个 argmin 中重新绑定了 k。所以整个事情可能是错误的;我没有尝试运行此代码。
    2. range 的参数可能都应该加 1,因为 Python 从 0 开始计数,而不是 1。(通常从 1 开始计数是个坏主意)。
    3. 我假设 G 是类型为 { from : { to : length } } 的字典。换句话说,邻接表表示。
    4. 我推断 C 是类型为 { (set(int),int) : int } 的字典。我可能是错的。
    5. 我使用set 作为C 的键。在真正的 Python 中,您必须先转换为 frozen_set。转换只是繁琐的工作,所以我把它省略了。
    6. 我不记得 Python 中的集合运算符了。我似乎记得它使用|&amp; 而不是+-
    7. 我没有写subsets_of_size。这相当复杂。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-09-08
      • 1970-01-01
      • 2015-04-28
      • 2017-11-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-10-24
      相关资源
      最近更新 更多