2010-03-26 34 views

回答

21

Dynamic programming。考慮到它是DAG,它也在Longest path problem中引用。

下面的代碼從維基百科:

algorithm dag-longest-path is 
    input: 
     Directed acyclic graph G 
    output: 
     Length of the longest path 

    length_to = array with |V(G)| elements of type int with default value 0 

    for each vertex v in topOrder(G) do 
     for each edge (v, w) in E(G) do 
      if length_to[w] <= length_to[v] + weight(G,(v,w)) then 
       length_to[w] = length_to[v] + weight(G, (v,w)) 

    return max(length_to[v] for v in V(G)) 
+1

這隻返回路徑的長度。代碼是否可以輕鬆修改以返回路徑? – oschrenk 2012-04-02 20:46:12

+1

是的,與大多數DP問題一樣 - 跟蹤以前的情況並重新開始。 – Larry 2012-07-17 16:34:43

+2

'topOrder(G)'是[topological order](https://en.wikipedia.org/wiki/Topological_sorting) – 2016-10-29 14:22:32

4

只要該圖是無環,所有你需要做的是否定的邊緣權重和運行任何最短路徑算法。

編輯:很明顯,你需要一個支持負權重的最短路徑算法。另外,來自維基百科的算法似乎有更好的時間複雜性,但我會在這裏留下我的答案供參考。

+0

,我們是否保持負面權重爲負? :p – Hellnar 2010-03-27 00:26:33

+0

@Hellnar:不,如果你在原始圖中有負值,他們應該變爲正值。 w'= - (w) – 2010-03-27 09:55:06

1

可以通過關鍵路徑方法來解決:
1.找到一個拓撲排序
2.找到關鍵路徑
參見[Horowitz 1995],Fundamentals of Data Structures in C++,Computer Science Press,New York。

貪婪策略(例如Dijkstra)不會工作,不管:1。使用「max」而不是「min」2.將正面權重轉換爲負面3.給出非常大的數字M並使用M-w作爲權重。

相關問題