简体   繁体   中英

Runtime of singe-source shortest paths in the directed acyclic graphs algorithm

Here is the Algorithm:

Topologically sort the Vertices of G
Initialize - Single - Source(G,s)
for each vertex u, taken in topologically sorted order
     for each vertex v in G.Adjacent[u]
         Relax(u,v,w) 
  • Topological sort has Runtime O(V + E), where V - is the number of Vertices and E - is a number of edges
  • Initialize - Single - Source(G,s) has runtime O(V)
  • The main question is double for Loop: The running time of the double for Loop is O(V + E). But I cannot understand, why it's not O(V*E)? Because for every Vertices we go through every edge and normally one nested Loop(all together 2 for Loops) have complexity O(N^2), but in this case it's not true.

For each vertex u , you only iterate through the edges that go out from u . Each distinct edge is visited only once, and that's why the algorithm takes O(V+E) time.

This assumes you are using a graph representation (like adjacency lists, not a matrix) that allows quick access to every vertex's adjacent edges. The topological sort also requires this.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM