Exercises
Thirteen problems covering the whole course: searches, topological sort and components, spanning trees, single-source and all-pairs shortest paths, and flows. Try each one on paper first. Every problem has a short Answer to check yourself against and a full Solution; several solutions include a program that confirms the result, which you can edit and run.
Tip: Draw the graph. For searches, write the queue or the recursion stack next to it after every step; for shortest paths, write the current estimate on every vertex; for flows, write "flow/capacity" on every edge. Most mistakes in this material are a neighbour visited in the wrong order or a residual edge forgotten, and a drawing exposes both.
| # | Exercise | Practises |
|---|---|---|
| 1 | Distances by hand | BFS |
| 2 | Timestamps and edge kinds | DFS, edge classification |
| 3 | How many schedules? | topological sort, Kahn |
| 4 | One edge to connect them all | strongly connected components |
| 5 | The bottleneck property | MST, cut property |
| 6 | The second-best spanning tree | MST, cycle property |
| 7 | Why not add a constant? | Dijkstra, negative weights |
| 8 | What pass guarantees | Bellman-Ford, relaxation |
| 9 | Solve or refute | difference constraints |
| 10 | Potentials by hand | Johnson's reweighting |
| 11 | Flow and cut | max-flow min-cut |
| 12 | When Hall's condition fails | bipartite matching |
| 13 | A cycle in time | DFS, undirected graphs |
Exercise 1: Distances by hand
Run BFS from on the undirected graph with edges (neighbours in alphabetical order). Give every distance and the parent of every vertex.
Answer
: ; ; ; . Parents: ; ; ; .
Solution
The queue evolves as , , , , , . is discovered from , which leaves the queue before , and from , which leaves before ; when is dequeued, is already discovered. See Breadth-First Search.
from collections import deque
adj = {}
for u, v in ["AB", "AC", "BD", "CD", "CF", "DE", "EF"]:
adj.setdefault(u, []).append(v); adj.setdefault(v, []).append(u)
d, parent, q = {"A": 0}, {"A": None}, deque("A")
while q:
u = q.popleft()
for v in sorted(adj[u]):
if v not in d:
d[v], parent[v] = d[u] + 1, u
q.append(v)
print(d)
print(parent){'A': 0, 'B': 1, 'C': 1, 'D': 2, 'F': 2, 'E': 3}
{'A': None, 'B': 'A', 'C': 'A', 'D': 'B', 'F': 'C', 'E': 'D'}
Exercise 2: Timestamps and edge kinds
Run DFS on the directed graph with edges , , , , , starting at , neighbours in alphabetical order. Give every interval and classify every edge.
Answer
, , , . Tree edges , , ; back edge ; cross edge .
Solution
From the search goes to (time 2), then (time 3). finds gray: a back edge. finishes at 4 and at 5. Back at , is discovered at 6; finds black with : a cross edge. finishes at 7 and at 8. The back edge shows the cycle , as the white-path argument predicts. Rules in Classifying the Edges of a DFS.
Exercise 3: How many schedules?
A DAG has edges , , , . How many topological orders does it have, and which one does Kahn's algorithm with a min-heap return?
Answer
4 orders. Kahn's algorithm returns .
Solution
must come after both and and before both and . So every order is (an order of ), , (an order of ): . The min-heap always takes the smallest ready name: and are ready first, wins, then , then , then before . See Kahn's Algorithm.
Exercise 4: One edge to connect them all
A directed graph has edges , , , , , , . Find its strongly connected components and its component graph. Which single new edge makes the whole graph strongly connected?
Answer
Components , , , with component graph . Adding any edge from to a vertex of , for example , makes it strongly connected.
Solution
The component graph is a path, a DAG with one source and one sink . An edge from the sink component to the source component closes a cycle through all three components, merging them. In general, if the component graph has sources and sinks (and more than one component), at least new edges are needed, since every source needs a new entering edge and every sink a new leaving one; here . The program checks the claim with Kosaraju's algorithm.
def scc_count(adj):
seen, order = set(), []
def v1(u):
seen.add(u)
for w in adj.get(u, []):
if w not in seen: v1(w)
order.append(u)
for u in sorted(adj):
if u not in seen: v1(u)
radj = {}
for u in adj:
for w in adj[u]:
radj.setdefault(w, []).append(u)
comp, count = {}, 0
def v2(u):
comp[u] = count
for w in radj.get(u, []):
if w not in comp: v2(w)
for u in reversed(order):
if u not in comp:
v2(u); count += 1
return count
g = {"A": ["B"], "B": ["C"], "C": ["A", "D"], "D": ["E"], "E": ["D", "F"], "F": []}
print("components:", scc_count(g))
g["F"] = ["A"]
print("after adding F -> A:", scc_count(g))components: 3
after adding F -> A: 1
Exercise 5: The bottleneck property
Prove that a minimum spanning tree also minimizes the largest edge weight among all spanning trees: no spanning tree has a smaller maximum edge.
Answer
If a spanning tree had all edges lighter than the heaviest edge of , then removing from defines a cut that must cross with some edge , and ; swapping for would give a lighter spanning tree than .
Solution
Let be a heaviest edge of the MST , and suppose a spanning tree has maximum edge weight smaller than . Removing splits into two components, which define a cut . is connected, so some edge crosses this cut, and by assumption. Then is a spanning tree (the two components are reconnected) of weight , contradicting minimality. The converse is false: a bottleneck spanning tree need not be minimum. This is the exchange argument of the cut property.
Exercise 6: The second-best spanning tree
For the graph of Kruskal's algorithm (edges , , , , , , , , , , , ), find the weight of the lightest spanning tree that differs from the MST.
Answer
- The MST weighs 34, and three different swaps cost only 1 more: add and remove , add and remove , or add and remove .
Solution
A second-best spanning tree differs from the MST by a single swap: add one non-tree edge , which closes a cycle with the tree path from to , and remove the heaviest tree edge on that path. Trying every non-tree edge, with the path-maximum check, gives the best swap. The program does it with a plain search per candidate.
edges = [("A", "B", 4), ("A", "C", 3), ("B", "C", 2), ("B", "D", 5), ("C", "E", 7), ("D", "E", 6),
("D", "F", 9), ("E", "G", 8), ("F", "G", 10), ("F", "H", 1), ("G", "H", 11), ("E", "F", 12)]
parent = {v: v for v in "ABCDEFGH"}
def find(x):
while parent[x] != x:
x = parent[x]
return x
mst = []
for u, v, w in sorted(edges, key=lambda e: e[2]):
if find(u) != find(v):
parent[find(u)] = find(v); mst.append((u, v, w))
base = sum(w for *_, w in mst)
def heaviest_on_path(tree, u, v):
adj = {}
for a, b, w in tree:
adj.setdefault(a, []).append((b, w)); adj.setdefault(b, []).append((a, w))
best, stack = {u: (0, None)}, [u]
while stack:
x = stack.pop()
for y, w in adj[x]:
if y not in best:
best[y] = max(best[x], (w, (x, y))); stack.append(y)
return best[v]
options = []
for u, v, w in edges:
if (u, v, w) not in mst:
heavy, e = heaviest_on_path(mst, u, v)
options.append((base + w - heavy, f"add {u}{v}:{w}, remove {e[0]}{e[1]}:{heavy}"))
print("MST weight", base)
for cost, how in sorted(options)[:3]:
print(cost, how)MST weight 34
35 add AB:4, remove AC:3
35 add CE:7, remove DE:6
35 add FG:10, remove FD:9
Exercise 7: Why not add a constant?
Give a graph with one negative edge where adding the same constant to every weight (to make them non-negative) changes which path is shortest.
Answer
Edges , , . The shortest path from to is (weight 0). Adding 3 to every edge gives weights 6, 0 and 4, and now (4) beats (6).
Solution
Adding to every edge adds to a path with edges, so it penalizes paths with more edges, and the two-edge path loses to the one-edge path. Johnson's reweighting adds instead, which shifts all paths between the same two vertices by the same amount. With from an added source, for , and the new weights are , and : (3) still wins.
Exercise 8: What pass guarantees
Prove that after pass of Bellman-Ford, is at most the weight of every path from to with at most edges, whatever order the edges are relaxed in.
Answer
Induction on : a path with at most edges is a path with at most edges to some plus an edge , which pass relaxes after has already reached the required bound.
Solution
For , the only path with 0 edges is from to , and . Assume the claim after pass , and let be a path to with at most edges. If it has fewer than edges, the claim holds already, since estimates never increase. Otherwise is a path to some with edges, followed by . After pass , , and during pass the edge is relaxed, so afterwards . The claim gives the correctness of Bellman-Ford directly: some shortest path has at most edges, and never drops below (upper-bound property).
Exercise 9: Solve or refute
Find a solution of the system , , , , , . Then add and show that the new system has no solution.
Answer
(or any shift of it). With added, the constraints and add up to .
Solution
Build the constraint graph: an edge of weight for each , and start every estimate at 0. Bellman-Ford converges to . In the second system the edges (weight ) and (weight 1) form a cycle of weight .
def solve(n, cons): # cons: (j, i, b) means x_j - x_i <= b
x = [0] * (n + 1)
for _ in range(n):
for j, i, b in cons:
x[j] = min(x[j], x[i] + b)
ok = all(x[j] - x[i] <= b for j, i, b in cons)
return x[1:] if ok else "no solution (negative cycle)"
system = [(1, 2, 3), (2, 3, -2), (3, 1, 1), (1, 3, 0), (4, 1, -1), (4, 3, 2)]
print(solve(4, system))
print(solve(4, system + [(3, 2, 1)]))[0, -2, 0, -1]
no solution (negative cycle)
Exercise 10: Potentials by hand
A directed graph has edges , , , , . Compute Johnson's potentials and all reweighted edges.
Answer
for . New weights: , , , , .
Solution
With every estimate starting at 0 (the edges from the added source), Bellman-Ford gives , (nothing negative enters ), (through ) and . Then : for example . Every new weight is , and the edges on shortest paths from the added source become 0. See Johnson's Algorithm and Reweighting.
edges = [("A", "B", 2), ("B", "C", -4), ("A", "C", 1), ("C", "D", 3), ("B", "D", -1)]
h = {v: 0 for v in "ABCD"}
for _ in range(4):
for u, v, w in edges:
h[v] = min(h[v], h[u] + w)
print("h:", h)
print("new weights:", ", ".join(f"{u}{v}:{w + h[u] - h[v]}" for u, v, w in edges))h: {'A': 0, 'B': 0, 'C': -4, 'D': -1}
new weights: AB:2, BC:0, AC:5, CD:0, BD:0
Exercise 11: Flow and cut
Find a maximum flow and a minimum cut of the network with capacities , , , , , , , .
Answer
Maximum flow 7; the minimum cut is the two edges into , and , of capacity .
Solution
Augment, for example, by 3, by 3, and by 1: value 7. The edges into have total capacity 7, so no flow can do better, and by the max-flow min-cut theorem both are optimal. The program confirms it with Edmonds-Karp and reads off the residual cut.
from collections import deque
cap = {("S", "A"): 5, ("S", "B"): 4, ("A", "B"): 2, ("A", "C"): 3, ("B", "D"): 5,
("C", "T"): 4, ("D", "C"): 2, ("D", "T"): 3}
flow = dict.fromkeys(cap, 0)
def bfs():
prev, q = {"S": None}, deque("S")
while q:
u = q.popleft()
for (a, b), c in cap.items():
if a == u and flow[(a, b)] < c and b not in prev:
prev[b] = (a, b, 1); q.append(b)
if b == u and flow[(a, b)] > 0 and a not in prev:
prev[a] = (a, b, -1); q.append(a)
return prev
value = 0
while "T" in (prev := bfs()):
steps, v = [], "T"
while prev[v]:
a, b, sign = prev[v]; steps.append((a, b, sign)); v = a if sign == 1 else b
bottleneck = min(cap[(a, b)] - flow[(a, b)] if s == 1 else flow[(a, b)] for a, b, s in steps)
for a, b, s in steps:
flow[(a, b)] += s * bottleneck
value += bottleneck
S = set(bfs())
print("maximum flow", value)
print("cut S-side", sorted(S), "edges", [f"{a}{b}" for (a, b) in cap if a in S and b not in S])maximum flow 7
cut S-side ['A', 'B', 'C', 'D', 'S'] edges ['CT', 'DT']
Exercise 12: When Hall's condition fails
Workers and machines : and can only run machine 1, can run 1 or 2, can run 3 or 4. What is the size of a maximum matching, and which set of workers shows that no perfect matching exists?
Answer
3, for example -1, -2, -3. The set has only one machine among its neighbours.
Solution
Hall's theorem (Discrete Mathematics) says a matching saturating all workers exists if and only if every set of workers has at least neighbours. has the single neighbour , so one of stays unmatched, and the maximum is at most 3. The matching above has 3 edges. In flow terms, the minimum cut has capacity 3; see Maximum Bipartite Matching.
Exercise 13: A cycle in time
Show how to decide whether an undirected graph given by adjacency lists has a cycle in time, independent of .
Answer
Run DFS and stop at the first back edge. Before it finds one, every edge examined is a tree edge (or the edge back to the parent), and a forest has at most edges, so at most list entries are examined.
Solution
In an undirected DFS every edge is a tree edge or a back edge. While no back edge has appeared, the explored edges form a forest, which has fewer than edges; each is seen at most twice (once from each end, the second time as the edge to the parent, which is skipped). The first entry that is neither leads to an already discovered vertex: a back edge, so a cycle, and the search stops. Hence at most list entries are examined before the answer is known, plus for the outer loop. The same argument shows that a graph with always has a cycle.
Test yourself
Which algorithm finds shortest paths in a DAG with negative edge weights in linear time?
- Dijkstra
- Relaxing edges in topological order
- Prim
- BFS
You need all-pairs shortest paths on a sparse graph with negative edges and no negative cycles. Which algorithm is asymptotically best?
- Floyd-Warshall,
- Johnson's algorithm,
- Repeated squaring,
- runs of Dijkstra on the original weights
A maximum flow has value 12. What is the capacity of a minimum cut?
- At least 13
- Exactly 12
- At most 11
- It depends on the algorithm