Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/algorithm/11.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Algorithm 有向无权图中的最长无环路径_Algorithm_Graph - Fatal编程技术网

Algorithm 有向无权图中的最长无环路径

Algorithm 有向无权图中的最长无环路径,algorithm,graph,Algorithm,Graph,在无权有向无环图中,可以使用什么算法来寻找最长路径?。如果它是DAG,则在中也会引用它 以下代码来自Wikipedia: 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 def

在无权有向无环图中,可以使用什么算法来寻找最长路径?

。如果它是DAG,则在中也会引用它

以下代码来自Wikipedia:

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))
算法dag最长路径为
输入:
有向无环图G
输出:
最长路径的长度
长度_to=数组,带有int类型的| V(G)|元素,默认值为0
对于拓扑序(G)中的每个顶点v,do
对于E(G)do中的每条边(v,w)

如果只要图是非循环的,那么只要将length_设置为[w],您所需要做的就是对边权重求反并运行任何最短路径算法


编辑:显然,您需要支持负权重的最短路径算法。另外,维基百科的算法似乎具有更好的时间复杂度,但我将在这里留下我的答案供参考。

维基百科有一个算法:


看起来他们使用了权重,但应该使用所有设置为1的权重。

可以通过关键路径方法解决:
1.查找拓扑排序
2.找到关键路径
参见[霍洛维茨1995 ],C++中的数据结构基础,计算机科学出版社,纽约。
贪婪策略(例如Dijkstra)不会起作用,不管:1。使用“最大”而不是“最小”2。将正权重转换为负3。给出一个非常大的数字M,并使用M-w作为权重。

我们是否将负权重保持为负p@Hellnar:不,如果原始图表中的权重为负数,则它们应变为正数。w'=-(w)这只返回路径的长度。代码可以很容易地修改以返回路径吗?是的,与大多数DP问题相同——跟踪上一个问题并返回。topOrder(G)
是循环中G的顶点列表,因此从“源”(无输入边)开始,以“汇”(无输出边)结束a但在需要时更容易遵循基本原理。