Proofs: Longest path in a directed acyclic graph
These are the human proofs of Longest path in a directed acyclic graph, at full length.
DAG-LONGEST-PATH computes the heaviest path from the source full
This proof shows: correctness, termination.
Let be a directed multigraph with real weights and a source . For let be the largest weight of a directed path from to , and if there is none.
Termination and cycles. Kahn's algorithm stops, and it returns an order of all vertices if and only if is acyclic (see Kahn's algorithm). If has a cycle, line L1 stops the run. From now on is acyclic, and is a topological order: each arc has before . The loops of lines L4 and L6 are finite, so the run stops.
is finite or . In an acyclic graph a directed walk never repeats a vertex, since the part between two visits of the same vertex would be a cycle. So there are finitely many paths from , and the maximum exists when the set is not empty.
Lemma 1 (the recurrence). , and for , , with the convention that the maximum over an empty set is and .
Proof. The only path from to is the path of one vertex, since any other would be a cycle, so . For , a path from to has a last arc , and without this arc is a path from to of weight at most . So , and is at most the right-hand side. Conversely, for an arc with , take a path from to of weight . The vertex is not on : if it were, the part of from to with the arc would be a cycle. So followed by is a path from to of weight , and is at least the right-hand side.
Lemma 2 (values are always weights of paths). At each moment, if , then following from gives a path from to of weight . In particular, .
Proof. Initially only is finite, and the path of one vertex has weight 0. Line L8 sets and while is the vertex being processed. By the induction hypothesis there is a path from to of weight , and is before in . After is processed, and never change, because line L8 only changes vertices that are heads of arcs out of the vertex being processed, and those are later in than it, while is already passed. So the parent chain of stays a path of weight , and adding the arc gives a walk of weight , which is a path because is acyclic.
Lemma 3 (invariant of line L4). When the loop of line L4 reaches , .
Proof. By induction on . Assume it for , and let . Every arc has with . When was processed, by the induction hypothesis. If , line L5 let pass, and line L7 at the arc made ; values only go up afterwards. If , this arc does not count in Lemma 1. So, for , by Lemma 1, and for , by line L3. With Lemma 2, , so .
Theorem. If has a cycle, DAG-LONGEST-PATH reports it. Otherwise it stops with for every vertex , and for each with the parent pointers give a path from to of the largest weight.
Proof. The first part is the statement on line L1. A vertex keeps its value after its turn in the loop, as the proof of Lemma 2 shows, so the final is the value of Lemma 3, which is . Lemma 2 then gives the path.