Graph with colored edges: the shortest paths with a color change of no more than k?

I have a directed graph with colored weighted edges. There are 2 colors. Each edge can have only 1 color. I want to find the shortest path with limited color changes. From one vertex there can be a maximum of 2 edges with two different colors and 2 edges with two different colors.

For example, in this graph:

The shortest path with three color changes will be. 9 At max, the 0color changes the shortest path 6+1+4=11, etc.

My solution is to recursively visit all possible paths and exchange, if recursion is found to be the best, which makes this problem exponential.

Is there a nonexponential solution to this problem?

+4
source share
2 answers

This can be solved in O (nm + n 2 log n) time by executing Dijkstra's algorithm on a correctly constructed graph.

To motivate intuition where we are going, suppose that the optimal path makes no more than one color change and begins with a red border. Therefore, the path does not follow either the blue edges, in which case we only follow the red edges, or this follows a certain number of red edges, then with a certain number of blue edges.

Think about what happens if you transform G as follows:

  • , G0 G1. node v G0 v0 node v G1 v1.
  • (u0, v0) (u0, v1).
  • G1.

G, . , , G0, , G1. G1 .

, . G0, . G0 G1, , . .

, node u node v, . , u, v0 v1. v0 - v0, . v1 - v1, . u v, .

, k . k G, G0, G1, G2,..., G (k-1). , , . G0 G0 G1. G1 G1 G2. G2 G2 G3 .. , G (k-1), , G (k-1). , , - node u0 node v_r u v, r , , . , r, , v_0, v_1,..., v_ (k-1).

, , . - , , , .

, ? , k , O (nk) O (mk), O (k (m + n)). Dijkstra O (mk + nk log nk), - O (mk + nk log nk).

O (mn + n 2 log n) : , , n - 1 . , n , . , . , k & ge; n, k n. k = n O (mn + n 2 log n).

, !

+6

, .

.

  • hashmap/dictionary, -, , .

  • k-way, , # 1, .

psudeocode :

  • ExtractMin(): min k- . # , . min , k-way ( ).

  • add (, , ): , , . min , min k-way , .

, , , .

, , . - :

if number_color_changes <= max_color_changes:
    data_structure.add(path, length, number_color_changes)

, .

. , Dijkstra , , , .

, , .

0

Source: https://habr.com/ru/post/1544365/


All Articles