علوم الحاسوب · الكتاب 3 · السنة الجامعية 1

University Computer Science — Year 1

هذا الكتاب غير متوفر بعد باللغة العربية. النسخ المتوفرة: English.

University Computer Science — Year 1 · السنة الجامعية 1

25Shortest Paths

From the Town Square to the Hospital, the shortest way is 6.3 kilometres long and takes nine minutes at the speed limits. Another way is a kilometre longer and takes a minute and a half less, because it uses the faster roads. Breadth-first search counts roads, neither metres nor seconds. This chapter weighs every road with a number, here its travel time or its length, and finds the paths of least total weight: from one place with Dijkstra’s algorithm when weights are not negative, with Bellman–Ford’s when they may be, in linear time when the graph is acyclic, and between all pairs of places at once with Floyd–Warshall’s.

You already know

The second book ran Dijkstra’s algorithm by hand on small maps. Binary heaps and priority queues were built in Chapter 18; topological orders and breadth-first search in Chapter 24; tables of subproblems in Chapter 23.

25.1 Weighted shortest paths

Definition 25.1 (Weight of a path, shortest path, weighted distance)

In a directed graph with a weight w(u,v)w(u, v) on each arc, the weight of a path is the sum of the weights of its arcs. The weighted distance δ(s,v)\delta(s, v) is the infimum of the weights of the paths from ss to vv: +∞+\infty if there is none, −∞-\infty if there are paths of arbitrarily small weight. A shortest path from ss to vv is a path of weight δ(s,v)\delta(s, v).

An undirected road is two arcs of the same weight. The town’s roads carry their length in metres, or their travel time at the speed limit, rounded to the second.

def roads(weight="seconds"):
    """adj[u] is a list of (v, w); a one-way road gives one arc, any other road two.
    The time of a road is its length at its speed limit, rounded to the second."""
    adj = {int(p["place_id"]): [] for p in rows("places")}
    for r in rows("roads"):
        a, b = int(r["from_place"]), int(r["to_place"])
        metres, kmh = int(r["length_m"]), int(r["speed_kmh"])
        w = metres if weight == "metres" else round(metres * 3.6 / kmh)
        adj[a].append((b, w))
        if r["one_way"] == "0":
            adj[b].append((a, w))
    return adj
Listing 25.1. The roads weighted by travel time code/bachelor-1/25-shortest-paths/listings/wgraph.py
$ python wgraph.py
30 places, 105 arcs, speed limits [30, 50, 70] km/h
from the Station: [('Town Hall', 120), ('River Park', 35), ('Hill Park', 35)]
Output 25.1. The road from the Station to the Town Hall is short, 1000 m, but limited to 30 km/h.

Definition 25.2 (Negative cycle)

A negative cycle is a cycle of negative weight. If one is reachable from ss and reaches vv, going round it again and again makes δ(s,v)=−∞\delta(s, v) = -\infty.

Proposition 25.3 (Subpaths of shortest paths)

Every subpath of a shortest path is a shortest path between its ends. And if there is no negative cycle, δ(s,v)≤δ(s,u)+w(u,v)\delta(s, v) \leq \delta(s, u) + w(u, v) for every arc u→vu \to v (the triangle inequality).

The proof is Exercise 25.9; it is cut and paste again, as in Chapter 23.

Definition 25.4 (Relaxation)

The algorithms keep an estimate dist[v]≥δ(s,v)\texttt{dist}[v] \geq \delta(s, v), with dist[s]=0\texttt{dist}[s] = 0 and +∞+\infty elsewhere at the start. To relax the arc u→vu \to v is to set dist[v]=dist[u]+w(u,v)\texttt{dist}[v] = \texttt{dist}[u] + w(u, v), and the parent of vv to uu, if that is smaller.

Every estimate is the weight of some path, the path of parents, so it never drops below the distance; and once dist[u]=δ(s,u)\texttt{dist}[u] = \delta(s, u), relaxing u→vu \to v for the last arc of a shortest path to vv gives dist[v]=δ(s,v)\texttt{dist}[v] = \delta(s, v). The algorithms differ only in the order in which they relax arcs.

Definition 25.5 (Shortest-path tree)

A shortest-path tree from ss is a rooted tree on the vertices reachable from ss, rooted at ss, whose path from ss to each vertex vv is a shortest path.

25.2 Dijkstra’s algorithm with a heap

Method 25.6 (Dijkstra’s algorithm)

With non-negative weights: keep a set of settled vertices, at first empty. Repeatedly settle the unsettled vertex of smallest estimate, and relax every arc leaving it.

A binary heap gives the smallest estimate. When an estimate decreases, the program pushes a new entry rather than moving the old one (lazy deletion); the stale entry is skipped when it comes off the heap.

def dijkstra(adj, s):
    """(dist, parent, pops): pops counts entries taken off the heap, stale or not."""
    dist, parent = {v: INF for v in adj}, {s: None}
    dist[s] = 0
    heap, settled, pops = [(0, s)], set(), 0
    while heap:
        d, u = heapq.heappop(heap)
        pops += 1
        if u in settled:  # a stale entry: u was settled with a smaller key
            continue
        settled.add(u)
        for v, w in adj[u]:
            if d + w < dist[v]:  # relax the arc u -> v
                dist[v], parent[v] = d + w, u
                heapq.heappush(heap, (dist[v], v))
    return dist, parent, pops


def path(parent, v):
    out = []
    while v is not None:
        out.append(v)
        v = parent[v]
    return out[::-1]
Listing 25.2. Dijkstra’s algorithm with a binary heap and lazy deletion code/bachelor-1/25-shortest-paths/listings/dijkstra.py

Theorem 25.7 (Dijkstra’s invariant)

With non-negative weights, every vertex uu has dist[u]=δ(s,u)\texttt{dist}[u] = \delta(s, u) when it is settled. So at the end dist holds the distances, and the parents form a shortest-path tree.

The proof is Exercise 25.10: if uu were the first vertex settled with a wrong estimate, a shortest path to uu would leave the settled set somewhere, at an arc x→yx \to y, and yy would have an estimate at most δ(s,u)\delta(s, u), smaller than uu’s.

Dijkstra’s algorithm from s, after settling s, then b, then a; the estimates are written beside the vertices. Settling b, at 1, lowers a from 4 to 3; settling a lowers c from 6 to 4. Then c is settled at 4 and t at 7.
Dijkstra’s algorithm from s, after settling s, then b, then a; the estimates are written beside the vertices. Settling b, at 1, lowers a from 4 to 3; settling a lowers c from 6 to 4. Then c is settled at 4 and t at 7.

Each vertex is settled once and each arc relaxed once, so at most mm entries are pushed, plus the first; each push or pop costs O(log⁡m)=O(log⁡n)O(\log m) = O(\log n), since m≤n2m \leq n^2. The total is O((n+m)log⁡n)O((n + m) \log n). A heap with decrease-key (Chapter 18) keeps one entry per vertex, at the same cost, and less memory.

$ python dijkstra.py
fastest: 7290 m in 445 s, 7 roads, 35 pops
  via North Bridge, River Park, Station, Hill Park, Market Hall, Museum
shortest: 6270 m in 539 s, 6 roads, 34 pops
  via North Bridge, River Park, Town Hall, Fire Station, Clinic
Output 25.2. The fastest and the shortest way from the Town Square to the Hospital; “pops” counts the entries taken off the heap, stale ones included.
The fastest route (solid, 445 s) and the shortest one (dashed, 6270 m), drawn from the data by figures/routes.py. They share their first two roads; then the fast one turns west through the Station onto faster roads, while the short one heads north.
The fastest route (solid, 445 s) and the shortest one (dashed, 6270 m), drawn from the data by figures/routes.py. They share their first two roads; then the fast one turns west through the Station onto faster roads, while the short one heads north.

25.3 Negative weights and Bellman–Ford

Weights may be negative: a reward, a gain of height, a refund. Dijkstra’s algorithm then fails, because a vertex can be settled before a cheaper path reaches it through a negative arc.

Dijkstra settles a at 2 and relaxes a t, giving t the estimate 3. Settling b at 3, the arc b a lowers a to 1, but a is settled and its arcs are not relaxed again: t keeps 3, though its distance is 2.
Dijkstra settles a at 2 and relaxes a→ta \to t, giving t the estimate 3. Settling b at 3, the arc b→ab \to a lowers a to 1, but a is settled and its arcs are not relaxed again: t keeps 3, though its distance is 2.
$ python dijkstra_neg.py
Dijkstra: {'s': 0, 'a': 1, 'b': 3, 't': 3}
true:     {'s': 0, 'a': 1, 'b': 3, 't': 2}
Output 25.3. The listing of Listing 25.2 on this graph.

Method 25.8 (Bellman–Ford algorithm)

Relax every arc, in any order; repeat, in rounds, until a round changes nothing. If round nn still changes an estimate, report a negative cycle.

def bellman_ford(adj, s):
    """(dist, parent, rounds), or None if a negative cycle is reachable from s."""
    dist, parent = {v: INF for v in adj}, {s: None}
    dist[s] = 0
    for rounds in range(1, len(adj) + 1):
        changed = False
        for u in adj:
            for v, w in adj[u]:
                if dist[u] + w < dist[v]:
                    dist[v], parent[v] = dist[u] + w, u
                    changed = True
        if not changed:
            return dist, parent, rounds  # a round without change: nothing will change
    return None  # still changing at round n: a negative cycle
Listing 25.3. Bellman–Ford, with a stop at the first quiet round code/bachelor-1/25-shortest-paths/listings/bellman_ford.py

Proposition 25.9 (Rounds of Bellman–Ford)

If no negative cycle is reachable from ss, then after kk rounds dist[v]=δ(s,v)\texttt{dist}[v] = \delta(s, v) for every vertex vv that has a shortest path of at most kk arcs; so n−1n - 1 rounds suffice and round nn changes nothing. If a negative cycle is reachable from ss, every round changes some estimate.

Proof. Without a reachable negative cycle, every reachable vv has a shortest path that is simple, so of at most n−1n - 1 arcs. By induction on kk: if s=v0,…,vk=vs = v_0, \dots, v_k = v is a shortest path, dist[vk−1]=δ(s,vk−1)\texttt{dist}[v_{k-1}] = \delta(s, v_{k-1}) after round k−1k - 1 (its prefix is a shortest path, Proposition 25.3), and round kk relaxes vk−1→vv_{k-1} \to v. Estimates never go below distances, so they stop changing. Conversely, if a round changes nothing, then dist[v]≤dist[u]+w(u,v)\texttt{dist}[v] \leq \texttt{dist}[u] + w(u, v) for every arc; summing along a reachable cycle, where every estimate is finite, gives 0≤0 \leq the weight of the cycle: no negative cycle is reachable. ∎

Each round costs O(n+m)O(n + m), so the whole costs O(nm)O(nm), far more than Dijkstra’s algorithm, but it accepts any weights.

$ python bellman_ford.py
roads in seconds: stable after 5 rounds out of at most 30, Hospital at 445 s
the negative arc: {'s': 0, 'a': 1, 'b': 3, 't': 2}
with the arc t -> b: None
Output 25.4. Five rounds suffice on the town, the last one quiet; the arc t→bt \to b closes the cycle b→a→t→bb \to a \to t \to b of weight −1-1.

Bellman published the method in 1958 as an algorithm for a routing problem; it also carries the name of Lester Ford, who studied the same kind of problem.

25.4 Shortest paths in a DAG

In a directed acyclic graph, relaxing the arcs leaving each vertex, the vertices taken in a topological order, gives all distances from ss in one pass, whatever the signs of the weights: when uu is reached, every arc entering uu has been relaxed, and by induction along the order dist[u]=δ(s,u)\texttt{dist}[u] = \delta(s, u). The cost is O(n+m)O(n + m), the topological order included. The same pass with maxima in place of minima gives longest paths, a problem that is hard in general graphs but easy without cycles.

Definition 25.10 (Critical path)

A project is a set of tasks with durations and prerequisites, which form a DAG. The earliest start of a task is the largest total duration of a chain of tasks that must precede it; a critical path is a chain of tasks of largest total duration: its length is the shortest possible duration of the project.

def critical_path(tasks):
    """(start, length, path): start[t] is the earliest day t can start."""
    start, via = {}, {}
    for t in topological(tasks):
        start[t], via[t] = 0, None
        for before in tasks[t][1]:  # relax the arc before -> t, keeping the maximum
            end = start[before] + tasks[before][0]
            if end > start[t]:
                start[t], via[t] = end, before
    last = max(tasks, key=lambda t: start[t] + tasks[t][0])
    path = [last]
    while via[path[-1]] is not None:
        path.append(via[path[-1]])
    return start, start[last] + tasks[last][0], path[::-1]
Listing 25.4. Earliest starts and a critical path, in topological order code/bachelor-1/25-shortest-paths/listings/dag_paths.py
$ python dag_paths.py
earliest start: design 0, database 3, interface 3, import 8,
  tests 8, manual 7, training 11, launch 12
project: 13 days; critical path: design > database > tests > training > launch
Output 25.5. A small software project: delay any task of the critical path and the launch is delayed.

The manual can start on day 7 and has until day 9, two days before training must start on day 11: it has two days of slack. The tasks of the critical path have none.

25.5 All pairs: Floyd–Warshall

For the distances between all pairs, one can run Dijkstra’s algorithm from every vertex, at a cost of O(n(n+m)log⁡n)O(n (n + m) \log n). A dynamic programme on the adjacency matrix is shorter to write and handles negative weights.

Method 25.11 (Floyd–Warshall algorithm)

Number the vertices 0,…,n−10, \dots, n - 1. Let Dk(i,j)D_k(i, j) be the smallest weight of a path from ii to jj whose intermediate vertices are all less than kk. Then D0(i,j)D_0(i, j) is 00 if i=ji = j, w(i,j)w(i, j) for an arc and +∞+\infty otherwise, and

Dk+1(i,j)=min⁡(Dk(i,j),  Dk(i,k)+Dk(k,j)).D_{k+1}(i, j) = \min\bigl(D_k(i, j),\; D_k(i, k) + D_k(k, j)\bigr).

The table is updated in place, kk in the outer loop; DnD_n is the distance table.

def floyd_warshall(adj):
    """(order, d, nxt): d[i][j] is the distance from order[i] to order[j], nxt[i][j]
    the index of the vertex after order[i] on a shortest path to order[j]."""
    order = list(adj)
    index = {v: i for i, v in enumerate(order)}
    n = len(order)
    d = [[0 if i == j else INF for j in range(n)] for i in range(n)]
    nxt = [[j if i == j else None for j in range(n)] for i in range(n)]
    for u in adj:
        for v, w in adj[u]:
            if w < d[index[u]][index[v]]:
                d[index[u]][index[v]], nxt[index[u]][index[v]] = w, index[v]
    for k in range(n):  # now paths may go through vertices 0..k
        for i in range(n):
            for j in range(n):
                if d[i][k] + d[k][j] < d[i][j]:
                    d[i][j] = d[i][k] + d[k][j]
                    nxt[i][j] = nxt[i][k]
    return order, d, nxt


def route(order, nxt, a, b):
    i, j = order.index(a), order.index(b)
    out = [a]
    while i != j:
        i = nxt[i][j]
        out.append(order[i])
    return out
Listing 25.5. Floyd–Warshall, with a table of next vertices to rebuild the paths code/bachelor-1/25-shortest-paths/listings/floyd.py

The triple loop costs Θ(n3)\Theta(n^3) and the tables Θ(n2)\Theta(n^2). On a dense graph, where mm is close to n2n^2, it beats nn runs of Dijkstra by a logarithm and more; on a sparse one, such as roads, nn runs of Dijkstra cost about n2log⁡nn^2 \log n and win when nn is large. Updating in place is safe: in round kk, the entries D(i,k)D(i, k) and D(k,j)D(k, j) do not change, since a path to or from kk gains nothing by going through kk again, without negative cycles.

$ python floyd.py
30 x 30 table, 27000 steps of the triple loop; equal to 30 runs of Dijkstra: True
Town Square -> Hospital: 445 s, 7 roads, same route as Dijkstra: True
Hospital -> Town Square: 445 s, 7 roads, same route as Dijkstra: True
Town Square -> Library: 98 s, 1 road, same route as Dijkstra: True
Library -> Town Square: 204 s, 2 roads, same route as Dijkstra: True
Output 25.6. All pairs in the town; the one-way road makes the return from the Library longer.

Floyd published the algorithm in 1962 as a short procedure for shortest paths; the same year, Warshall proved the same loop correct for the reachability relation, with “or” and “and” in place of “min” and “++”.

Definition 25.12 (Eccentricity, centre, diameter)

In a strongly connected weighted graph, the eccentricity of a vertex is its greatest distance to another vertex. A centre is a vertex of smallest eccentricity, the radius; the diameter is the greatest eccentricity, the largest distance between two vertices.

25.6 Exercises

Exercise 25.1 ★

In the graph drawn for Dijkstra’s algorithm, give the order in which the vertices are settled and the final distances, starting from a instead of s.

Solution

Solution of Exercise 25.1.

From a: settle a at 0, which gives c 1 and t 6; settle c at 1, which lowers t to 4; settle t at 4. The vertices s and b are not reachable: their distance is +∞+\infty.

Exercise 25.2 ★

Run Bellman–Ford from ss on the arcs a→ca \to c (2), b→ab \to a (−1-1), s→as \to a (4), s→bs \to b (2), b→cb \to c (5), relaxed in this order in every round. Give the estimates after each round, and the number of rounds.

Solution

Solution of Exercise 25.2.

Round 1: a→ca \to c and b→ab \to a do nothing (infinite estimates), then a=4a = 4, b=2b = 2, c=7c = 7. Round 2: c=6c = 6, then a=1a = 1. Round 3: c=3c = 3. Round 4 changes nothing: four rounds, the last one quiet. The shortest path to cc, s→b→a→cs \to b \to a \to c, has three arcs, and this order of relaxation needs a round for each.

Exercise 25.3 ★

Three vertices 0, 1, 2 have arcs 0→10 \to 1 (5), 1→21 \to 2 (2), 0→20 \to 2 (9), 2→02 \to 0 (1). Give the matrices D0D_0, D1D_1 and D2D_2 of Floyd–Warshall.

Solution

Solution of Exercise 25.3.

Rows are the sources, columns the targets, ∞\infty for no path:

D0=(059∞021∞0),D1=(059∞02160),D2=(057∞02160),D_0 = \begin{pmatrix} 0 & 5 & 9 \\ \infty & 0 & 2 \\ 1 & \infty & 0 \end{pmatrix},\quad D_1 = \begin{pmatrix} 0 & 5 & 9 \\ \infty & 0 & 2 \\ 1 & 6 & 0 \end{pmatrix},\quad D_2 = \begin{pmatrix} 0 & 5 & 7 \\ \infty & 0 & 2 \\ 1 & 6 & 0 \end{pmatrix},

and D3D_3 adds D(1,0)=2+1=3D(1, 0) = 2 + 1 = 3. Going through 0 helps only paths starting at 2, the only vertex with an arc into 0: 2→0→12 \to 0 \to 1.

Exercise 25.4 ★

In the project of Output 25.5, the database now takes 3 days. What are the new length and critical path?

Solution

Solution of Exercise 25.4.

The database ends on day 6, the interface on day 7: the tests now start on day 7, training on day 10 and the launch on day 11. The project takes 12 days, and the critical path is design, interface, tests, training, launch: shortening a critical task by two days saved only one, because another path became critical.

Exercise 25.5 ★★

This version fixes a vertex’s distance when it is first pushed. Explain the output and the difference with Listing 25.2.

def dijkstra_push(adj, s):
    dist, heap = {s: 0}, [(0, s)]
    while heap:
        d, u = heapq.heappop(heap)
        for v, w in adj[u]:
            if v not in dist:  # fixed at the first discovery
                dist[v] = d + w
                heapq.heappush(heap, (dist[v], v))
    return dist
Listing 25.6. Fixed when pushed code/bachelor-1/25-shortest-paths/listings/exo_settle_push.py
{'s': 0, 'a': 5, 'b': 1}
Output 25.7. Arcs s→as \to a (5), s→bs \to b (1), b→ab \to a (1). Some lines are left out.
Solution

Solution of Exercise 25.5.

a is reached first from s, at 5, and fixed; the path s→b→as \to b \to a, of weight 2, is found later and ignored. Fixing at discovery is right for breadth-first search, where every arc has the same weight, so the first path found to a vertex has the fewest arcs. With weights, a vertex may only be fixed when it leaves the heap with the smallest key; until then, a cheaper path may still reach it.

Exercise 25.6 ★★

With the loop on kk innermost, 350 entries of the town’s table are wrong. Why?

    for i in range(n):
        for j in range(n):
            for k in range(n):
                d[i][j] = min(d[i][j], d[i][k] + d[k][j])
    return d
Listing 25.7. The loops in another order code/bachelor-1/25-shortest-paths/listings/exo_floyd_inner.py
wrong entries: 350 of 900
Output 25.8. Against Floyd–Warshall. Some lines are left out.
Solution

Solution of Exercise 25.6.

With kk innermost, the entry (i,j)(i, j) is computed once and for all, by trying every single intermediate vertex kk with the entries (i,k)(i, k) and (k,j)(k, j) as they are at that moment, which are not final when ii or jj comes later in the loops. A path that needs two intermediate vertices whose entries are computed too late is missed. With kk outermost, the entries Dk(i,k)D_k(i, k) and Dk(k,j)D_k(k, j) are complete for the vertices below kk before they are used.

Exercise 25.7 ★★

Compute the smallest weight of a path of at most kk arcs from ss to every vertex, with any weights, in O(k(n+m))O(k(n + m)), and test it.

Solution

Solution of Exercise 25.7.

def at_most_k(adj, s, k):
    dist = {v: INF for v in adj}
    dist[s] = 0
    for _ in range(k):
        before = dict(dist)  # relax from the previous round only: one more arc
        for u in adj:
            for v, w in adj[u]:
                if before[u] + w < dist[v]:
                    dist[v] = before[u] + w
    return dist
Paths of at most kk arcs code/bachelor-1/25-shortest-paths/exercises/at_most_k.py

By induction, after round rr, dist[v]\texttt{dist}[v] is the smallest weight of a path of at most rr arcs: such a path is either of at most r−1r - 1 arcs, or a path of at most r−1r - 1 arcs to some uu followed by u→vu \to v. Relaxing from the copy before is what keeps one arc per round; relaxing in place could chain several arcs in one round, as Bellman–Ford does on purpose. The test compares with a brute-force enumeration of walks.

Exercise 25.8 ★★

Each arc has a capacity, for instance the height limit of a road. Find, from ss, the paths whose smallest capacity is as large as possible, by a variant of Dijkstra’s algorithm, and justify it.

Solution

Solution of Exercise 25.8.

def widest(adj, s):
    width = {v: 0 for v in adj}
    width[s] = float("inf")
    heap, done = [(-width[s], s)], set()
    while heap:
        _, u = heapq.heappop(heap)
        if u in done:
            continue
        done.add(u)
        for v, c in adj[u]:
            b = min(width[u], c)  # the bottleneck of the path through u
            if b > width[v]:
                width[v] = b
                heapq.heappush(heap, (-b, v))
    return width
Widest paths code/bachelor-1/25-shortest-paths/exercises/widest.py

Extending a path can only lower its bottleneck, as adding a non-negative weight can only raise a length. So the proof of Theorem 25.7 works with “largest” for “smallest” and min⁡\min for ++: the unsettled vertex of largest width has its final width. The heap holds negated widths, since heapq pops the smallest.

Exercise 25.9 ★★

Prove Proposition 25.3.

Solution

Solution of Exercise 25.9.

Let PP be a shortest path from ss to vv and QQ its piece from xx to yy. If a path Q′Q' from xx to yy were lighter, replacing QQ by Q′Q' in PP would give a walk from ss to vv lighter than PP; without negative cycles a walk can be shortened to a path no heavier, by cutting out its closed sub-walks, a contradiction. For the triangle inequality, a shortest path to uu followed by u→vu \to v is a walk of weight δ(s,u)+w(u,v)\delta(s, u) + w(u, v), and δ(s,v)\delta(s, v) is at most that (if δ(s,u)=+∞\delta(s, u) = +\infty, there is nothing to prove).

Exercise 25.10 ★★★

Prove Theorem 25.7.

Solution

Solution of Exercise 25.10.

Estimates are always weights of paths, so dist[v]≥δ(s,v)\texttt{dist}[v] \geq \delta(s, v). Suppose uu is the first vertex settled with dist[u]>δ(s,u)\texttt{dist}[u] > \delta(s, u); u≠su \neq s, and uu is reachable, or its estimate would be +∞=δ(s,u)+\infty = \delta(s, u). Take a shortest path from ss to uu; it starts in the settled set and ends outside it. Let x→yx \to y be its first arc leaving the set. xx was settled with dist[x]=δ(s,x)\texttt{dist}[x] = \delta(s, x), and relaxed x→yx \to y, so dist[y]≤δ(s,x)+w(x,y)=δ(s,y)≤δ(s,u)<dist[u]\texttt{dist}[y] \leq \delta(s, x) + w(x, y) = \delta(s, y) \leq \delta(s, u) < \texttt{dist}[u], using Proposition 25.3 and the non-negative weights after yy. So y≠uy \neq u and yy has a smaller key than uu: it would have been settled first. Contradiction. For the tree: each vertex’s parent was settled before it, so the parent links have no cycle, and along them the weights add up to the distances.

Exercise 25.11 ★★★

In a weighted DAG, count the shortest paths from ss to every vertex in O(n+m)O(n + m), and prove it.

Solution

Solution of Exercise 25.11.

def count_paths(adj, order, s):
    """order: a topological order of the vertices."""
    dist, ways = {v: INF for v in adj}, {v: 0 for v in adj}
    dist[s], ways[s] = 0, 1
    for u in order:
        if dist[u] == INF:
            continue
        for v, w in adj[u]:
            if dist[u] + w < dist[v]:
                dist[v], ways[v] = dist[u] + w, ways[u]
            elif dist[u] + w == dist[v]:
                ways[v] += ways[u]
    return dist, ways
Counting shortest paths in a DAG code/bachelor-1/25-shortest-paths/exercises/dag_count.py

By induction along the topological order: when uu is taken, every arc entering uu has been relaxed, so dist[u]=δ(s,u)\texttt{dist}[u] = \delta(s, u), and ways[u] is the sum of ways[x] over the arcs x→ux \to u with δ(s,x)+w(x,u)=δ(s,u)\delta(s, x) + w(x, u) = \delta(s, u): each shortest path to uu is a shortest path to such an xx followed by the arc, in exactly one way. When an estimate drops, the count restarts from the new predecessor’s. Each arc is handled once: O(n+m)O(n + m), with zero weights allowed, since there is no cycle.

Exercise 25.12 ★★★

Write a function that returns a negative cycle of a graph, as a list of vertices, or None, in O(nm)O(nm).

Solution

Solution of Exercise 25.12.

def negative_cycle(adj):
    """Bellman--Ford from a virtual source with an arc of weight 0 to every vertex."""
    dist, parent = {v: 0 for v in adj}, {v: None for v in adj}
    last = None
    for _ in range(len(adj)):
        last = None
        for u in adj:
            for v, w in adj[u]:
                if dist[u] + w < dist[v]:
                    dist[v], parent[v] = dist[u] + w, u
                    last = v
        if last is None:
            return None
    for _ in range(len(adj)):  # walk back n steps: we are now on the cycle
        last = parent[last]
    cycle, v = [last], parent[last]
    while v != last:
        cycle.append(v)
        v = parent[v]
    return cycle[::-1]
A negative cycle code/bachelor-1/25-shortest-paths/exercises/negative_cycle.py

Starting every estimate at 0 is Bellman–Ford from a new vertex joined to all others by arcs of weight 0, so every cycle is reachable. If round nn still lowers the estimate of some vertex, the parent links contain a cycle: following them back nn steps from that vertex cannot avoid repeating a vertex. On a cycle of parent links, each estimate was set from the next one along the cycle, and summing the inequalities shows that its weight is negative. The cost is nn rounds of O(m)O(m).

25.7 Problem: The centre of Brenmoor

Problem 25.1

Weekend problem — The centre of Brenmoor

Where in Brenmoor should the new ambulance station go, so that the farthest place is as close as possible? Travel times are those of Listing 25.1.

def eccentricities(order, d):
    return {v: max(d[i]) for i, v in enumerate(order)}
Listing 25.8. Eccentricities from the distance table code/bachelor-1/25-shortest-paths/listings/centre.py
$ python centre.py
Town Hall         349 s =  5.8 min, farthest South Bridge
River Park        364 s =  6.1 min, farthest Post Office
Station           399 s =  6.7 min, farthest Post Office
Old Mill          675 s = 11.2 min, farthest Post Office
Post Office       675 s = 11.2 min, farthest Old Mill
centre: Town Hall, radius 349 s; diameter 675 s = 11.2 min
Output 25.9. The three most central places, the two least central, the centre and the diameter.

Part I — Modelling.

  1. Compute the travel time of a road of 1360 m at 50 km/h, as the program does.
  2. Why does the Station have an arc of 120 s to the Town Hall but only 35 s to River Park?
  3. How many arcs does the town have, and why not 106?
  4. Why are the weights in whole seconds, and what does rounding cost on a route of seven roads?
  5. Why must a one-way road be an arc, not an edge, in this model?
  6. Could the weights be negative here? Which algorithms would still apply?

Part II — Dijkstra from the Town Square.

  1. Read the fastest and the shortest routes to the Hospital, and compare their lengths and times.
  2. Why did the search pop 35 entries for 30 places?
  3. Bound the number of pops in terms of nn and mm.
  4. Why do the parents form a tree, and why is it a shortest-path tree?
  5. Up to which place do the two routes agree, and what does Proposition 25.3 say of their first parts?
  6. Breadth-first search found a route of six roads to the Hospital in Output 24.5: compare it with the two routes.

Part III — All pairs.

  1. Prove by induction on kk that Dk(i,j)D_k(i, j), as defined by the recurrence, is the smallest weight of a path from ii to jj with all intermediate vertices less than kk.
  2. Deduce that DnD_n is the distance table.
  3. Show that the in-place update computes the same table.
  4. Explain how nxt rebuilds a route, and why nxt[i][j] = nxt[i][k] is right.
  5. Why do the Library and the Town Square have different distances in the two directions?
  6. Compare the costs of Floyd–Warshall and of 30 runs of Dijkstra on the town.

Part IV — The centre.

  1. Explain max(d[i]): why is the distance from a place to itself harmless?
  2. Read the centre, the radius and the diameter.
  3. Why does the Post Office appear as farthest for several places?
  4. Show that the diameter is at most twice the radius when every road is two-way.
  5. Does that bound hold for Brenmoor, with its one-way road?
  6. State the named result, the town’s centre and diameter, with its proof.
Solution

Solution of Problem 25.1.

1. 1360×3.6/50=97.921360 \times 3.6 / 50 = 97.92, rounded to 98 s.

2. The road to the Town Hall is 1000 m at 30 km/h; the road to River Park is 680 m at 70 km/h.

3. 105: two arcs for each of the 52 two-way roads and one for the one-way road.

4. Integers make sums and comparisons exact, and ties really are ties. Each road’s time is off by at most half a second, so a route of seven roads by at most 3.5 s.

5. An edge could be driven both ways, and routes would use the one-way road against its direction.

6. No, times are positive. Bellman–Ford and Floyd–Warshall would still apply, but not Dijkstra’s algorithm.

7. The fastest route is 7290 m in 445 s, the shortest 6270 m in 539 s: 1020 m more, 94 s less.

8. 30 pops settle the places; the other 5 are stale entries, left behind when an estimate was lowered after its vertex had been pushed.

9. One push for the source and at most one per relaxed arc, so at most m+1m + 1 pushes and pops: 106 here.

10. The parent of vv was settled before vv, so following parents goes back in the order of settling and ends at ss: no cycle, a tree. By Theorem 25.7, its paths are shortest.

11. Up to River Park, by the North Bridge. The first part of each route is itself fastest, respectively shortest, to River Park; here the fastest and the shortest ways to River Park are the same.

12. It is the shortest route, by chance: fewest roads and fewest metres need not agree. The fastest route has seven roads.

13. For k=0k = 0, a path without intermediate vertex is the empty path or a single arc. A best path from ii to jj with intermediate vertices less than k+1k + 1 avoids kk, and weighs Dk(i,j)D_k(i, j), or passes through kk once (without negative cycles it need not pass twice), and splits into two paths with intermediate vertices less than kk, each best by cut and paste: Dk(i,k)+Dk(k,j)D_k(i, k) + D_k(k, j).

14. With k=nk = n, every vertex may be intermediate: Dn(i,j)=δ(i,j)D_n(i, j) = \delta(i, j).

15. In round kk, the entries D(i,k)D(i, k) and D(k,j)D(k, j) do not change, since Dk(k,k)=0D_k(k, k) = 0 without negative cycles. So every entry read in round kk has its value of DkD_k, whether it was updated already or not.

16. nxt[i][j] is the first step of a best path from ii to jj; the route follows it until jj. When the path through kk wins, its first step is the first step of the best path from ii to kk.

17. Road 1 goes one way, from the Town Square to the Library, in 98 s; the way back needs two roads and 204 s.

18. Floyd–Warshall makes 27 000 steps of the triple loop. One Dijkstra run handles 135 vertices and arcs with heap operations of about 7 comparisons: about 30 runs ×\times 1000, of the same order. Floyd–Warshall’s loop is simpler; Dijkstra’s runs would win on a larger town, since n3n^3 grows faster than n2log⁡nn^2 \log n.

19. max(d[i]) is the largest distance from place ii; the 0 of d[i][i]d[i][i] never wins when there are other places, all at positive distance.

20. The centre is the Town Hall, with radius 349 s (5.8 min); the diameter is 675 s (11.2 min), between the Old Mill and the Post Office.

21. The Post Office lies on the east edge of the map, the Old Mill in the south-west corner: they are far from most places, and from each other.

22. With symmetric distances, for any uu and vv and the centre cc: δ(u,v)≤δ(u,c)+δ(c,v)=δ(c,u)+δ(c,v)≤2r\delta(u, v) \leq \delta(u, c) + \delta(c, v) = \delta(c, u) + \delta(c, v) \leq 2r.

23. The proof uses δ(u,c)=δ(c,u)\delta(u, c) = \delta(c, u), which the one-way road can break; the bound still holds here, 675≤698675 \leq 698, but it is checked, not proved.

24. The town’s centre and diameter: the Floyd–Warshall table is the distance table (questions 13–15), so the eccentricities computed from it are exact: the Town Hall is the centre, every place within 349 s of it, and no two places are more than 675 s apart. The ambulance station belongs at the Town Hall.

المصطلحات المعرَّفة في هذا الفصل

عرض كل المصطلحات (1050) في المسرد