ADCSBT1for u in order:2 for v, w in graph[u]:3 if dist[u] + w < dist[v]:4 dist[v] = dist[u] + w5 parent[v] = u#1#2#3#4#5#62637−2123u
Places: the front number is dist, the cheapest cost from S so farArrows: one way, with a weight; −2 is a negative weightTokens: u walks the order; dist[u] + w travels each arrowSix places joined by one-way arrows with weights; one weight is negative. The number on each place is dist, the cheapest cost from S found so far. The places are visited once, in topological order. For each arrow out, dist[u] + w travels along the arrow and replaces the far end's dist when it is cheaper. Every arrow into a place is relaxed before the place is visited, so one pass gives the exact answer in O(V + E) time.

The problem

  1. Six places joined by one-way arrows. Each arrow has a cost, its weight: S to A costs 2. B to C costs −2, a refund. No loop of arrows, so this is a DAG. Goal: the cheapest total cost from S to every place.

One pass in order

Why it works

The whole function in Python

import math
from graphlib import TopologicalSorter

def dag_shortest(graph, source):
    preds = {u: [] for u in graph}
    for u in graph:
        for v, w in graph[u]:
            preds[v].append(u)
    order = list(TopologicalSorter(preds).static_order())
    dist = {u: math.inf for u in graph}
    parent = {u: None for u in graph}
    dist[source] = 0
    for u in order:
        for v, w in graph[u]:
            if dist[u] + w < dist[v]:
                dist[v] = dist[u] + w
                parent[v] = u
    return dist, parent

graph = {
    "S": [("A", 2), ("B", 6)],
    "A": [("B", 3), ("C", 7)],
    "B": [("C", -2)],
    "C": [("D", 1), ("T", 2)],
    "D": [("T", 3)],
    "T": [],
}
print(dag_shortest(graph, "S"))

What happens

# step 1/10 · Arrows with costs
a weighted DAG: one-way arrows, no directed cycle
the cost of a path = the sum of its arrow weights
  S -> A   2
  S -> B   6
  A -> B   3
  A -> C   7
  B -> C  −2
  C -> D   1
  C -> T   2
  D -> T   3

in Python, each node lists (next node, weight) pairs:
graph = {
    "S": [("A", 2), ("B", 6)],
    "A": [("B", 3), ("C", 7)],
    "B": [("C", -2)],
    "C": [("D", 1), ("T", 2)],
    "D": [("T", 3)],
    "T": [],
}

This is DAG relaxation from MIT 6.006 Lecture 11, AcyclicSP in Sedgewick and Wayne §4.4, and DAG-SHORTEST-PATHS in CLRS §22.2 (4th ed.; §24.2 in the 3rd). All three relax the arrows of each node in topological order and run in O(V + E) time. Negative weights are fine here because a DAG has no cycle: no path can loop back to make itself cheaper again and again. Bellman-Ford handles negative weights on any graph, at O(V·E) cost.