# Define single source shortest path algorithm

Algorithm 5: (shortest paths from topological order) This runs in linear time (with the possible exception of finding the ordering), and works even when the graph has negative length edges.You can even use it to find longest paths: just negate the lengths of all the edges.

Just like with Prim's algorithm, we can use heaps to perform the hard part of each iteration (finding the best edge) in logarithmic time.Here's another ordering that always works: define a topological ordering of a directed graph to be one in which, whenever we have an edge from x to y, the ordering visits x before y.If we can define such an ordering, then we can do something like algorithm 2, and be sure that the predecessor of a vertex x is always processed before we process x itself.The idea is to go back to algorithms 1 and 2, which required you to visit the vertices in some order.In those algorithms we defined the order to be sorted by distance from s, which as we have seen works for positive weight edges, but not if there are negative weights.

## Define single source shortest path algorithm

A final observation is that d(s,x) must be less than d(s,t), since d(s,x)=d(s,t) length(x,t) and we are assuming all edges have positive length.Therefore if we only know the correct value of x we can find a shortest path: Algorithm 1: We will want to use something like this idea to compute shortest paths without already knowing their lengths.This is known as the single source shortest path problem (s is the source). It turns out that computing this extra information makes things easier, because then we can put together information about paths with fewer edges to get paths with more edges.The basic problem: Find the "best" way of getting from s to t where s and t are vertices in a graph.