Sub topic 3
Reading Negative Cycles from the Diagonal
This chapter assumes you have read the earlier floyd_warshall and fw_path code. It also assumes you can read Big-O notation.
Reading Negative Cycles from the Diagonal
Floyd-Warshall starts with dist[i][i] = 0. That value can only drop below zero if the algorithm finds a walk from i back to i with negative total weight, which is a negative cycle. After the run, check whether dist[i][i] < 0 for any i. Every vertex on a negative cycle gets a negative diagonal entry. A pair (i, j) has no defined shortest path when some k with dist[k][k] < 0 is reachable from i and can reach j.
All-Pairs Path Reconstruction with a Next-Hop Matrix
nxt[i][j] stores the first vertex after i on the best known path to j. When the path through k wins, the update nxt[i][j] = nxt[i][k] keeps the first hop toward k. To get the path, follow nxt from i until you reach j.
Choosing an Algorithm
| Situation | Algorithm | Time |
|---|---|---|
| One source, weights ≥ 0 | Dijkstra | O(E log V) |
| One source, negative weights | Bellman-Ford | O(VE) |
| All pairs, dense graph | Floyd-Warshall | O(V³) |
| All pairs, sparse, negative weights | Johnson | O(VE log V) |
Johnson's Algorithm for Sparse All-Pairs Problems
- Add a new vertex
qwith a 0-weight edge to every vertex. - Run Bellman-Ford from
qto get a potentialh(v). If Bellman-Ford finds a negative cycle, stop. - Reweight each edge as
w'(u, v) = w(u, v) + h(u) - h(v). The new weights are never negative. - Run Dijkstra from every vertex, then convert each result back with
d(u, v) = d'(u, v) - h(u) + h(v).
Transitive Closure as a Floyd-Warshall Variant
To ask only whether j is reachable from i, replace the min-plus update with boolean logic: reach[i][j] = reach[i][j] or (reach[i][k] and reach[k][j]).
Application: Finding Currency Arbitrage with Logarithmic Weights
A sequence of trades makes a profit when the product of its exchange rates is greater than 1. Set each edge weight to -log(rate). A product greater than 1 then becomes a weight sum less than 0, so an arbitrage opportunity is a negative cycle.
import math
def has_arbitrage(rates):
n = len(rates)
dist = [[-math.log(rates[i][j]) for j in range(n)] for i in range(n)]
for k in range(n):
for i in range(n):
for j in range(n):
if dist[i][k] + dist[k][j] < dist[i][j]:
dist[i][j] = dist[i][k] + dist[k][j]
return any(dist[i][i] < -1e-12 for i in range(n))
# rates[i][j]: units of currency j per unit of currency i
rates = [
[1.0, 0.9, 0.8],
[1.12, 1.0, 0.9],
[1.25, 1.1, 1.0],
]
print(has_arbitrage(rates)) # True: 0 -> 1 -> 0 yields 0.9 * 1.12 = 1.008Exercise
A graph has 10,000 vertices and 30,000 edges, some with negative weights, and you need all-pairs distances. Should you use Floyd-Warshall or Johnson's algorithm, and why?
Show answer
Use Johnson's algorithm. It runs in O(VE log V), about 10^4 × 3×10^4 × 14 ≈ 4×10^9 operations. Floyd-Warshall runs in O(V³) = 10^12 operations. Johnson also needs only adjacency lists, while Floyd-Warshall needs a V×V matrix.
Exercise
After Floyd-Warshall, dist[2][2] = -3. What does this tell you about vertex 2?
Show answer
Vertex 2 lies on a negative cycle. Shortest paths are undefined for every pair (i, j) where i can reach 2 and 2 can reach j.