60 likes | 86 Views
This text explains the proof of correctness for an algorithm using induction on the size of a set S. It also discusses the failure of Dijkstra's algorithm in the presence of negative edge costs and introduces a modified algorithm for such cases. The text concludes with the concept of topological order in acyclic graphs.
E N D
Proof of Correctness By induction on |S|, at end of loop: • For all v S, v.dist is equal to the length of the shortest path from s to v. • For all v V – S, v.dist is the length of the shortest path from s to v that lies wholly within S, except v itself. G=(V,E) v S “known” s V -S “unknown” CSE 373, Autumn 2001
The proof • Basis step. |S| = 1. The shortest path from s to itself has length 0. A path from s to v V – S wholly within S except for v consists of a single edge (s, v). v.dist = cvw in the algorithm. • Ind. step. Suppose v is chosen. If v.dist is not the length of a shortest path from s to v, then there must be a shorter path P. The path P must contain some vertex other than v that is not in S. (By ind. hyp. #2.) CSE 373, Autumn 2001
Induction step, cont’d x S P s • Let x be the first such vertex in P. But then x.dist < v.dist (why?), and so x should have been chosen, not v. Contradiction. Therefore, P must not exist, and v.dist is the length of the shortest path from s to v. • #2 is true because of the decrease() operation. (why?) v CSE 373, Autumn 2001
Negative Edge Costs x S P s • Dijkstra’s algorithm fails. • Idea: Get rid of the idea of known and unknown vertices. • Place s on the queue. • Dequeue a vertex and update distances of adjacent vertices, and place an adjacent vertex in the queue if its distance was lowered. v CSE 373, Autumn 2001
void Graph::weightedNegative(Vertex s) { Queue q(NUM_VERTICES); Vertex v, w; q.enqueue(s); s.dist = 0; while (!q.isEmpty()) { v = q.dequeue(); for each w adjacent to v if (v.dist + cvw < w.dist) { w.dist = v.dist + cvw; w.path = v; if (w is not already in q) q.enqueue(w); } } } } running time: O(|V| · |E|) CSE 373, Autumn 2001
Acyclic Graphs 1 5 -8 2 1 4 3 • Idea: We do not need to choose a vertex with minimum cost from an unknown set. Instead, choose the vertices in topological order. • Running time: O(|V| + |E|) s 3 4 2 2 1 CSE 373, Autumn 2001