如何从固定节点开始获取DAG中最长的路径?

时间:2012-05-26 01:37:51

标签: directed-acyclic-graphs topological-sort longest-path

我想知道如何从节点0(最小节点)开始在DAG中获取最长路径

我搜索了维基并获得了以下算法:

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))

但我不知道如何实现它,当然我写的以下代码不起作用:(topo是拓扑排序节点)

public static int longestPath(int[] topo){
    int[] dist = new int[topo.length];

    for(int i:topo){
        if(isArc(node,i)){
            if(dist[i]<dist[node]+1){
                dist[i] = dist[node] + 1;
            }
        }
    }
    return getMax(dist);
}

我该怎么办?谢谢!

此外,你能给我一个算法来计算从0到n-1的不同路径的数量吗?

0 个答案:

没有答案