[英]Is there an algorithm to find the minimum cost path in a directed rooted tree (arborescence)?
這可以在 O( n ) 時間內完成,其中n是節點數。 解決方案是遞歸的:
葉節點的最小成本路徑是微不足道的——它只是節點本身,具有節點自己的成本。
要找到內部節點的最小成本路徑,對其所有子節點進行遞歸調用,並為其最小成本路徑選擇成本最低的子節點。 路徑的成本等於節點自身的成本加上該子節點的路徑成本。
要恢復路徑,只需從函數中返回成本和路徑。 遞歸情況必須使用當前節點擴展路徑。
總運行時間為 O( n ),因為為內部節點完成的非遞歸工作與子節點的數量成正比。 運行時間不能漸近改進,但可以在實踐中使用分支定界算法進行優化,該算法跟蹤迄今為止的最低成本路徑,並拒絕超過它的路徑。
這是 Python 中的一個示例:
class Node:
def __init__(self, cost, children=()):
self.cost = cost
self.children = children
def __repr__(self):
return 'Node({})'.format(self.cost)
root = Node(1, (
Node(2, (
Node(5, (Node(9),)),
Node(6, (Node(9),)),
Node(9),
)),
Node(3, (
Node(8, (Node(9),)),
Node(9),
)),
Node(4, (Node(9),)),
))
def min_cost_path(node):
if not node.children:
return [node], node.cost
else:
# list of (path, cost) pairs
options = [min_cost_path(c) for c in node.children]
path, cost = min(options, key=lambda option: option[1])
path.append(node)
return path, cost + node.cost
例子:
>>> path, cost = min_cost_path(root)
>>> path
[Node(9), Node(2), Node(1)]
>>> cost
12
請注意,路徑以相反的順序返回。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.