Reputation: 2723
Let
G(V,E)
, a directed graph with weighted edges (w:E -> R
) and ar
inV
. It is known that for eachu
there's a lightest path (by weights) which is also a shortest path (by edges), fromr
tou
. Describe an algorithm to find lightest paths fromr
to eachu
.
So what I thought about is simply running a BFS algorithm from r
with a simple change; When we reach a vertex v
, we sort all edges coming out of it and put vertices in queue by edges order (from smallest to largest).
This way we are getting a graph of shortest paths (As BFS should do) but we also prefer the lightest one from two shortest paths.
Let's assume my algorithm is correct, the problem is that it's not the most efficient one, since we have to sort all edges which summed up to O(|E|lg |E|)
.
How can it be done in linear time (O(|V|+|E|
)?
Upvotes: 1
Views: 419
Reputation: 76386
Following is the psuedocode for BFS from Introduction To Algorithms:
BFS(G,s)
for each vertex u in V[G] - {s}
do color[u] <-- white
d[u] <-- infinity
pi[u] <-- nil
color[s] <-- gray
d[s] <-- 0
pi[s] <-- nil
Q <-- {s}
while Q != empty set
do u <-- head[Q]
for each v in Adj[u]
do if color[v] = white
then color[v] <-- gray
d[v] <-- d[u] + 1
pi[v] <-- u
EnQueue(Q,v) DeQueue(Q)
color[u] <-- black
Your question states that
It is known that for each u there's a lightest path (by weights) which is also a shortest path (by edges), from r to u.
Note that, by definition, this is recursive.
You can, therefore, modify it as follows:
Add to each node also c[u]
(the cost of u), and initialize all to infinity. Also, add cp[u]
, the "cost parent" of u.
When you encounter a node v in the adjacency of u, and v is not black, check if the cost of u + the cost of the edge is lower than the current cost of v. If so, update both the cost of v, and make its cost parent u.
Upvotes: 2