ENع
→DAG shortest paths
الدرس 35 · Shortest paths and spanning trees

Shortest paths in a DAG

لم يُترجم بعد؛ يُعرض باللغة الإنجليزية

14 دقيقة10 خطوات5 أسئلةAdvanced
عن هذا الدرس

When a weighted graph has no directed cycle, you do not need Dijkstra's heap or Bellman-Ford's repeated rounds. Sort the nodes topologically, then relax the arrows out of each node exactly once, in that order. Watch it run on six places with one negative arrow, and see why a single pass gives the exact cheapest cost in O(V + E) time. The lessons "Topological sort" and "Bellman-Ford and negative edges" cover the two ideas this one combines.

ستتعلّم

حدّد ما تشعر بأنك أتقنته. هذا التقييم الذاتي لا يؤثر في درجة الدرس.

شكل 35 · تفاعلي
01 / 10

Arrows with costs

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.

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": [],
}
جارٍ تحميل الرسم…
أو ← →
اقرأ الدرس خطوة بخطوة
  1. Arrows with costs

    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.

    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": [],
    }
  2. Line them up first

    First, a topological sort lists the places so every arrow points forward: S, A, B, C, D, T. Here every arrow points left to right. So when we reach a place, every arrow into it starts at a place we have already passed.

    topological order: S A B C D T
    every arrow u -> v has u earlier in the list:
      S (#1) -> A (#2)
      S (#1) -> B (#3)
      A (#2) -> B (#3)
      A (#2) -> C (#4)
      B (#3) -> C (#4)
      C (#4) -> D (#5)
      C (#4) -> T (#6)
      D (#5) -> T (#6)
    
    preds = node -> nodes with arrows into it
    order = list(TopologicalSorter(preds).static_order())
  3. Start: 0 here, ∞ elsewhere

    Each place keeps dist: the cheapest cost found so far. S costs 0 to reach from itself. Every other place starts at ∞ (infinity), meaning no path found yet. These numbers only ever go down.

    dist = {u: math.inf for u in graph}
    dist["S"] = 0
    S 0 · A ∞ · B ∞ · C ∞ · D ∞ · T ∞
    
    dist[v] is always the cost of some real path to v (or ∞),
    so it can only be too high, never too low
  4. Relax the arrows out of S

    Visit S. For each arrow out, ask: is dist[S] plus the weight cheaper than the far end’s dist? 0 + 2 = 2 beats ∞, so A becomes 2. 0 + 6 = 6 beats ∞: B becomes 6. This check is relaxing an arrow.

    for v, w in graph["S"]:
        if dist["S"] + w < dist[v]: dist[v] = dist["S"] + w
      S -> A: 0 +  2 =  2  vs  ∞  dist[A] = 2
      S -> B: 0 +  6 =  6  vs  ∞  dist[B] = 6
  5. A finds a cheaper B

    Visit A, whose dist is 2. Going on to B costs 2 + 3 = 5, cheaper than the 6 from the direct arrow, so B drops to 5 and remembers A as its parent. C gets 2 + 7 = 9 for now.

    u = A, dist[A] = 2
      A -> B: 2 +  3 =  5  vs  6  dist[B] = 5
      A -> C: 2 +  7 =  9  vs  ∞  dist[C] = 9
    parent[B] = A   (the last step of the best path to B)
  6. A negative arrow helps

    Visit B, now 5. Its only arrow costs −2: 5 + (−2) = 3, cheaper than 9. C drops to 3. The longer path S, A, B, C is cheaper than the short one through A alone. The order makes the negative weight safe.

    u = B, dist[B] = 5
      B -> C: 5 + −2 =  3  vs  9  dist[C] = 3
    best path to C so far: S -> A -> B -> C  (2 + 3 − 2 = 3)
    the direct route S -> A -> C costs 9
  7. C reaches D and T

    Visit C, now 3. Both arrows into C were already relaxed, so 3 is final. C sends 3 + 1 = 4 to D and 3 + 2 = 5 to T. Both beat ∞.

    u = C, dist[C] = 3  (final: arrows A -> C and B -> C are done)
      C -> D: 3 +  1 =  4  vs  ∞  dist[D] = 4
      C -> T: 3 +  2 =  5  vs  ∞  dist[T] = 5
  8. Not every try wins

    Visit D, now 4. Its arrow to T gives 4 + 3 = 7, but T already has 5. 7 is not cheaper, so T keeps 5. Visiting T relaxes nothing: it has no arrows out. One pass, and we are done.

    u = D, dist[D] = 4
      D -> T: 4 +  3 =  7  vs  5  no change
    u = T: no arrows out
    
    dist: S 0 · A 2 · B 5 · C 3 · D 4 · T 5
  9. Why one pass is enough

    The cheapest path to any place v arrives from some place u before v in the order. By the time we visit v, u was final and its arrow to v was relaxed. So dist[v] is final too. The parent arrows trace each best path.

    claim: when the loop reaches v, dist[v] is the true cheapest cost
    proof by induction along the order:
      the best path to v ends with some arrow u -> v
      u is earlier, so dist[u] is already exact
      relaxing u -> v set dist[v] <= dist[u] + w = the best cost
      and dist[v] is never below a real path cost, so it is equal
    
      A  2  via S -> A
      B  5  via S -> A -> B
      C  3  via S -> A -> B -> C
      D  4  via S -> A -> B -> C -> D
      T  5  via S -> A -> B -> C -> T
  10. Linear time: O(V + E)

    The topological sort is O(V + E). Then each place is visited once and each arrow relaxed once: 6 visits, 8 relaxations. Total O(V + E). Bellman-Ford needs O(V·E) for any graph; Dijkstra needs no negative weights.

    V = 6 visits, E = 8 relaxations, each O(1)
    topological sort: O(V + E)
    total: O(V + E)
    
    single-source shortest paths (MIT 6.006 L11):
      DAG relaxation  DAGs only, any weights    O(V + E)
      Bellman-Ford    any graph, any weights    O(V·E)
      Dijkstra        any graph, weights >= 0   O(V log V + E)

اختبار يتاح بعد الخطوة الأخيرة.