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).
, !