鱼C论坛

 找回密码
 立即注册
查看: 3077|回复: 4

[已解决]有序最短路径问题求助,具体问题如下

[复制链接]
发表于 2022-5-20 22:08:49 | 显示全部楼层    本楼为最佳答案   
  1. import sys

  2. def tsp(distances):
  3.     n = len(distances)
  4.     all_points_set = set(range(n))

  5.     # memo keys: tuple(sorted_points_in_path, last_point_in_path)
  6.     # memo values: tuple(cost_thus_far, next_to_last_point_in_path)
  7.     memo = {(tuple([i]), i): tuple([0, None]) for i in range(n)}
  8.     queue = [(tuple([i]), i) for i in range(n)]

  9.     while queue:
  10.         prev_visited, prev_last_point = queue.pop(0)
  11.         prev_dist, _ = memo[(prev_visited, prev_last_point)]

  12.         to_visit = all_points_set.difference(set(prev_visited))
  13.         for new_last_point in to_visit:
  14.             new_visited = tuple(sorted(list(prev_visited) + [new_last_point]))
  15.             new_dist = prev_dist + distances[prev_last_point][new_last_point]

  16.             if (new_visited, new_last_point) not in memo:
  17.                 queue += [(new_visited, new_last_point)]
  18.             memo[(new_visited, new_last_point)] = min(
  19.                 memo.get((new_visited, new_last_point), (float('inf'), None)),
  20.                 (new_dist, prev_last_point))

  21.     optimal_path, optimal_cost = retrace_optimal_path(memo, n)

  22.     return optimal_path, optimal_cost

  23. def retrace_optimal_path(memo: dict, n: int) -> [[int], float]:
  24.     points_to_retrace = tuple(range(n))

  25.     full_path_memo = dict((k, v) for k, v in memo.items() if k[0] == points_to_retrace)
  26.     path_key = min(full_path_memo.keys(), key=lambda x: full_path_memo[x][0])

  27.     last_point = path_key[1]
  28.     optimal_cost, next_to_last_point = memo[path_key]

  29.     optimal_path = [last_point]
  30.     points_to_retrace = tuple(sorted(set(points_to_retrace).difference({last_point})))

  31.     while next_to_last_point is not None:
  32.         path_key = (points_to_retrace, next_to_last_point)
  33.         _, next_to_last_point = memo[path_key]

  34.         optimal_path = [path_key[1]] + optimal_path
  35.         points_to_retrace = tuple(sorted(set(points_to_retrace).difference({path_key[1]})))

  36.     return optimal_path, optimal_cost
复制代码

在这段代码中,distances是一个二维数组,表示每两个城市之间的距离。tsp函数返回一个元组,第一个元素是一个列表,表示最优路径(城市的顺序),第二个元素是这个路径的总成本。

这个算法的时间复杂度是O(n^2 * 2^n),空间复杂度是O(n * 2^n)。这是因为算法需要枚举所有可能的路径,并且需要记住之前计算过的路径的成本。其中,n是城市的数量。

请注意,这个算法假设距离矩阵是对称的,也就是说,从城市A到城市B的距离和从城市B到城市A的距离是相同的。如果这个假设不成立,那么你需要修改这个算法,使其可以处理这种情况。
小甲鱼最新课程 -> https://ilovefishc.com
回复

使用道具 举报

发表于 2023-10-23 05:38:46 | 显示全部楼层
旅行商问题噢~
小甲鱼最新课程 -> https://ilovefishc.com
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2025-10-2 02:24

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表