在我的经济学研究中,我目前正在处理一个特定的最短路径问题:
给定一个带权边的有向确定性动态图,我需要找到从源点S出发通过N条边的最短路径。该图可以有环,边权可以为负数,并且路径允许多次经过一个顶点或边。
是否有一种高效的算法解决这个问题?
在我的经济学研究中,我目前正在处理一个特定的最短路径问题:
给定一个带权边的有向确定性动态图,我需要找到从源点S出发通过N条边的最短路径。该图可以有环,边权可以为负数,并且路径允许多次经过一个顶点或边。
是否有一种高效的算法解决这个问题?
“恰好有N
条边”的限制使得这个问题比没有该限制的问题容易得多。基本上,您可以解决N = 0(只是起始节点),然后使用它来解决N = 1(起始节点的所有邻居),然后是N = 2(解决N = 1的邻居,对于连接到多个节点的节点,采用最低成本路径),以此类推。
伪代码(使用{field: val}
表示“具有名为field
且值为val
的字段的记录”):
# returns a map from node to cost, where each key represents
# a node reachable from start_node in exactly n steps, and the
# associated value is the total cost of the cheapest path to
# that node
cheapest_path(n, start_node):
i = 0
horizon = new map()
horizon[start_node] = {cost: 0, path: []}
while i <= n:
next_horizon = new map()
for node, entry in key_value_pairs(horizon):
for neighbor in neighbors(node):
this_neighbor_cost = entry.cost + edge_weight(node, neighbor, i)
this_neighbor_path = entry.path + [neighbor]
if next_horizon[neighbor] does not exist or this_neighbor_cost < next_horizon[neighbor].cost:
next_horizon[neighbor] = {cost: this_neighbor_cost, path: this_neighbor_path}
i = i + 1
horizon = next_horizon
return horizon
我们使用edge_weight(node, neighbor, i)
来考虑动态权重,意思是“在时间步骤i
从node
到neighbor
的花费”。
这是单源最短路径算法(如Dijkstra算法)的退化版本,但它更简单,因为我们知道我们必须恰好走N步,所以我们不需要担心被困在负权重循环中,或者更便宜的路径等等。
edge_weight
考虑了动态边缘成本,因此称其为edge_weight(node, neighbor, i)
)不能工作。你看到了我没有看到的东西吗? - jacobm{A:0}
(只有起始点),地平线1是{A:2,B:1,C:4}
(使用T1权重到达每个节点的最便宜成本,从地平线0开始),地平线2是{A:0,B:3,C:2}
(使用地平线1开始的T2权重的最便宜扩展)。 - jacobm