Bellman-Ford: relaxing every edge V−1 times

Video lessonComing soon

1 A road that pays us

The last lesson ended on a small graph of one-way roads. Here we read it as bus routes between four towns, and each weight is the fare in rupees. The road from town 2 to town 1 pays back 4 rupees, so its fare is −4. We want the cheapest fare from town 0 to every town.

25−4100112532
The cheapest fares from town 0. The road 2 → 1 pays back 4

Dijkstra treats the nearest unfinished town as final. It finished town 1 at 2 and town 3 at 3. Only then did the road from town 2 offer 5 − 4 = 1 for town 1. With a done array, town 3 keeps the wrong fare of 3. With the stale check, towns come out of the heap again and again, and a negative cycle keeps the loop going forever.

We need a method that never trusts a fare too early, and that notices a loop that pays forever.

2 News travels one road per round

Each town keeps a label dist[v], as in the last lesson: the cheapest fare from town 0 it has heard of so far. Town 0's label is 0. Every other label is ∞, which means no route is known yet.

News moves along the roads. Town u tells town v: "You can come through me for dist[u] + w." Town v keeps the smaller of that and its own label. This is relaxing the road u → v, the same step as in the last lesson:

dist[v] = min(dist[v], dist[u] + w)

Dijkstra relaxes roads in a careful order, nearest town first. Bellman-Ford picks no order. In each round, it relaxes every road once, in the order the edge list gives them, and then it runs the next round. A label only goes down, and it always holds the fare of a real route. So after enough rounds, every label holds the cheapest fare.

3 Three rounds on the map

Our edge list happens to start at the far end of the map:

[1,3,1], [2,1,-4], [0,2,5], [0,1,2]

That is the worst order. In round 1, the roads out of towns 1 and 2 come first, while those towns still read ∞, so they carry no news. Only the last two roads, out of town 0, do anything. In the steps, the number by each town is its label, and the bold roads lowered a label in that round:

Bellman-Ford from town 0
25−41001∞2∞3∞
00∞1∞2∞3
Start: town 0 at 0, the rest at ∞

The same run as a table, with dist after each round:

Round0123Roads that lowered a label
start0∞∞∞
1025∞0 → 2, 0 → 1
201531 → 3, 2 → 1
301521 → 3
40152none

Each round, the right fares reach one road further along the cheapest route 0, 2, 1, 3. Town 2 is right after round 1, town 1 after round 2 and town 3 after round 3. Round 4 changes nothing.

4 Why V − 1 rounds are enough

Two short facts give the number of rounds.

A cheapest route needs at most V − 1 roads. A route of V roads passes V + 1 towns, so it visits some town twice and goes round a loop in between. Without a negative loop, cutting the loop out never makes the route dearer. So some cheapest route uses at most V − 1 roads, which is 3 on our map.

After round k, every town whose cheapest route has at most k roads is right. Let such a route end with the road u → v. The route up to u has k − 1 roads, so u is right after round k − 1. Round k relaxes u → v and brings v down to its cheapest fare. No label goes lower than that, because a label always holds a real route's fare.

So V − 1 rounds make every label right. A lucky edge order finishes sooner. The same roads listed from town 0 outward carry the news to town 3 in round 1. We come back to this lucky order in section 7.

Stop early. A round that changes nothing leaves the same labels for the next round, so that round changes nothing too. We stop at the first quiet round, which is round 2 in the lucky order.

5 The code

The code runs at most n − 1 rounds with the early stop, then one extra round: the negative-cycle check from the next section. As in the practice problem, 10⁸ stands for ∞, and a negative cycle gives [-1].

On our map, it returns [0, 1, 5, 2].

Cost. A round reads all E edges, and there are at most V rounds, so the time is O(V · E). The space is O(V) for dist. At V = 10⁵ and E = 2 × 10⁵ that is around 2 × 10¹⁰ steps, far past the time limit, so it gets TLE. Dijkstra needs a few million steps there. So Bellman-Ford suits small graphs, around V = 500 and E = 5,000, and graphs where Dijkstra goes wrong.

SPFA keeps a queue of the towns whose label just dropped, and relaxes only their roads. It is often much faster, but its worst case is still O(V · E).

6 Negative cycles: one more round

Now we add a road from town 3 to town 2 with fare 1. The loop 2 → 1 → 3 → 2 costs −4 + 1 + 1 = −2, so each trip round it makes a route 2 rupees cheaper, without end. This is a negative cycle. Towns 1, 2 and 3 have no cheapest fare at all.

25−4110123
The loop 2 → 1 → 3 → 2 adds up to −2

The labels never settle. After round 3 they read [0, 0, 3, 2], and round 4 still lowers all three of them.

Without a negative cycle, round V changes nothing, as section 4 showed. With a negative cycle that town 0 can reach, every round changes something. Suppose a round left every road of the loop alone. Then each loop road u → v has dist[v] ≤ dist[u] + w. We add up these three lines. Each label appears once on each side and cancels, which leaves 0 ≤ −2. That is false.

So the test is one extra round, round V. If any label drops, there is a negative cycle.

To list the affected towns, we take the towns whose label dropped in round V, and every town reachable from them with BFS or DFS. Here that is towns 1, 2 and 3. A negative cycle that town 0 cannot reach changes nothing. Its towns stay at ∞, and we skip them.

7 At most k roads: copy before each round

Some problems limit the number of roads, such as a trip with at most k stops. A trip with k stops takes k + 1 flights. Running k rounds is not enough. After round k the short routes are right, but within one round news can travel several roads. So a label may also hold a cheaper, longer route.

The lucky order shows it. With at most 1 road, town 3 cannot be reached at all. One round in this order goes all the way:

edges: [0,1,2], [0,2,5], [2,1,-4], [1,3,1]
round 1: 0 -> 1 sets 2
         0 -> 2 sets 5
         2 -> 1 sets 1
         1 -> 3 sets 2
dist = [0, 1, 5, 2]
town 3 got 2 by three roads

The fix is to read only last round's labels. We copy dist into prev before the round, and relax from prev:

repeat k times:
    prev = copy of dist
    for each edge (u, v, w):
        if prev[u] is not INF and prev[u] + w < dist[v]:
            dist[v] = prev[u] + w

Now news moves exactly one road per round, in any edge order. After rounds 1, 2 and 3, dist matches rows 1, 2 and 3 of our trace table, because the worst order also moved one road per round.

8 Mistakes, and when to use it

  • Relaxing from ∞. With edges [[0,1,5], [2,3,-3]] from town 0, town 2 is never reached. Without the skip, dist[3] becomes 10⁸ − 3 and looks like a real fare. With the largest int as ∞, a positive fare overflows instead.
  • No copy for the k-roads version. With at most 1 road, the lucky order gives town 3 a fare of 2 instead of ∞.
  • A negative undirected road. It is two one-way roads. A road between towns 1 and 2 with fare −4 makes the loop 1 → 2 → 1 at −8, a negative cycle by itself.
  • Off by one in the rounds. With two rounds, our worst order leaves dist[3] at 3 instead of 2. The check is round V, not round V − 1: round 3 lowers dist[3], and our map has no cycle.

The sign is roads with different costs and a question about the cheapest route. The details pick the method:

  • No negative weights and a big graph. Dijkstra, from the last lesson.
  • Negative weights, or a question about negative cycles. Bellman-Ford, if V · E stays within about 10⁷.
  • At most k edges. Bellman-Ford with the copy, k rounds.
  • Cheapest fares between every pair of towns, on a small graph. Floyd-Warshall, in the next lesson.
Before writing the rounds, check what the problem limits. Any number of roads needs V − 1 rounds and the check. At most k roads needs k rounds and the copy.

Practice it

Finished this lesson?

Mark it read and it is ticked on the roadmap and in the list.

Article

Send feedback

Thank you for helping. We read every report and fix what is wrong.

How do you feel about oneby7?

Sign in to oneby7

Keep your progress, your streak and your code, on any device.

New here? This creates your account too.