Finding the shortest path in a graph without any negative prefixes

后端 未结 9 1873
北荒
北荒 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:28

    Step 1: Note that your answer will be at most 2*n (if it exists).
    Step 2: Create a new graph with vertexes that are a pairs of [vertex][cost]. (2*n^2 vertexes)
    Step 3: Note that new graph will have all edges equal to one, and at most 2*n for each [vertex][cost] pair.
    Step 4: Do a dfs over this graph, starting from [start][0]
    Step 5: Find minimum k, such that [finish][k] is accesible.

    Total complexity is at most O(n^2)*O(n) = O(n^3)

    EDIT: Clarification on Step 1.
    If there is a positive cycle, accesible from start, you can go all the way up to n. Now you can walk to any accesible vertex, over no more than n edges, each is either +1 or -1, leaving you with [0;2n] range. Otherwise you'll walk either through negative cycles, or no more than n +1, that aren't in negative cycle, leaving you with [0;n] range.

提交回复
热议问题