- Run BFS from the source (let it be
s
) on the graph to find the
length of the shortest path from s
to the target t
, let it be d
. Also mark d(s,v)
- the distance from s
to any node v
.
- Create a subgraph
G'=(V',E')
of G
such that: v
is in V'
only if its distance from the source (s
) is at most d
- d(s,v) <= d
. e=(u,v)
is in E'
only if: both u
and v
are in V'
.
- Create a new graph
G*=(V*,E*)
, where V'=V*
, and an edge (u,v)
is in E*
if it is in E'
AND d(s,u) < d(s,v)
.
- Set a new weight function
w*(u,v) = -w(u,v)
, and run Bellman Ford on G*
using w*
.
- The heaviest shortest path in
G
from s
to t
is of weight -d(t)
, and the path found by BF is the matching one.
Time complexity of the algorithm is O(VE)
, since Bellman-Ford is the bottleneck.
Correctness Proof
Claim 1: The shortest path from s
to t
does not contain any cycles.
Proof is simple by removing the cycle we get a shorter path.
Claim 2: All shortest paths from s
to t
are in G'
Proof: Since all shortest paths from s
to t
are of length d
, and we eliminated only nodes with distance from s
longer than d
, we remove only nodes not needed for shortest paths.
Claim 3: All shortest paths from s
to t
are in G*
.
Proof: Assume we removed some edge (u,v)
in a shortest path, and let that path be s->...->x->u->v->y->...->t
. Note that the path v->y->..->t
is of length d-d(s,u)-1
(assuming d(s,u)
is minimal)
However, note that from construction of E*
, d(s,v) <= d(s,u)
(otherwise (u,v)
wouldn't have been removed). So, there is a path s->...->v->y->...->t
with distance from s
: d(s,v) + d-d(s,u)-1 <= d(s,u) + d - d(s,u) -1 <= d-1
- contradiction to minimality of d
.
Claim 4: There are no cycles in G*
.
Proof: Assume there is a cycle in G*
: v1->v2->vk->v1
. By definition of G', all nodes are reachable from s
. Without loss of generality, let us assume d(s,v1)
is minimal for all other d(s,vi)
(otherwise rotate indices to match this assumption). But there is a path v1->v2->...->vk->v1, and d(s,v1)=d(s,v1)
. This means at least for one edge (vi,vi+1)
in this path, d(vi) >= d(vi+1)
- which is contradicting the construction of E*
, and the cycle does not exist in G*.
Claim 5: The algorithm is correct.
From correctness of Bellman-Ford, and since G*
does not contain negative cycles (no cycles at all), BF will find the path with minimal weight according to w*
in G*
. This path is the one with maximal weight according to w
, from the construction of w*
.
since all shortest paths in G
also exist in G*
(and only them), this path is also the shortest path in G
with maximal weight.
QED