Finding the shortest path in a graph without any negative prefixes

后端 未结 9 1864
北荒
北荒 2021-01-31 11:15

Find the shortest path from source to destination in a directed graph with positive and negative edges, such that at no point in the path the sum of edges coming

9条回答
  •  清歌不尽
    2021-01-31 11:50

    The current assumptions are:

    1. yes there can be negative weight cycles.
    2. n is the number of edges.
    3. Assume that a O(n) length path exists if the problem has a solution.
    4. +1/-1 edge weights.

    We may assume without loss of generality that the number of vertices is at most n. Recursively walk the graph and remember the cost values for each vertex. Stop if the cost was already remembered for the vertex, or if the cost would be negative.

    After O(n) steps, either the destination has not been reached and there is no solution. Otherwise, for each of the O(n) vertices we have remembered at most O(n) different cost values, and for each of these O(n ^ 2) combinations there might have been up to n unsuccessful attempts to walk to other vertices. All in all, it's O(n ^ 3). q.e.d.

    Update: Of course, there is something fishy again. What does assumption 3 mean: an O(n) length path exists if the problem has a solution? Any solution has to detect that, because it also has to report if there is no solution. But it's impossible to detect that, because that's not a property of the individual graph the algorithm works on (it is asymptotic behaviour).

    (It is also clear that not all graphs for which the destination can be reached have a solution path of length O(n): Take a chain of m edges of weight -1, and before that a simple cycle of m edges and total weight +1).

    [I now realize that most of the Python code from my other answer (attempt for the first version of the problem) can be reused.]

提交回复
热议问题