30/40
Part 6 of 7 · The worked exampleLearn

Put the minute in the state, and the states have no cycles

3. The insight. The cheapest arrival at a district isn't one number, because it depends on when you arrive. Put the minute in the state. The cell cost[t][v] is the cheapest fee total for standing in district v at exactly minute t.

On the map, a road leads back from 1 to 0. As states, every road leads to a later minute:

The same two districts, as statesInteractive
(0, minute 0).

Every road moves from minute t to a later minute, so no state can lead back to itself. The road map has cycles, and the states don't. Filling the table by minute, from 0 up to the limit, is a topological order of the states.

import math


def cheapest_in_time(n, roads, fees, limit):
    # cost[t][v]: cheapest fees to be in v at minute t
    cost = [[math.inf] * n for _ in range(limit + 1)]
    cost[0][0] = fees[0]
    # minutes only go up: a topological order
    for t in range(limit + 1):
        for a, b, minutes in roads:
            if t + minutes <= limit:
                # both ways
                for u, v in ((a, b), (b, a)):
                    if cost[t][u] + fees[v] < cost[t + minutes][v]:
                        cost[t + minutes][v] = cost[t][u] + fees[v]
    best = min(cost[t][n - 1] for t in range(limit + 1))
    return None if best == math.inf else best


# (district, district, minutes)
ROADS = [(0, 2, 10), (0, 1, 2), (1, 2, 2), (2, 4, 6), (0, 3, 3), (3, 4, 3)]
FEES = [1, 5, 1, 12, 1]
print(cheapest_in_time(5, ROADS, FEES, 12))
print([cheapest_in_time(5, ROADS, FEES, limit) for limit in (5, 6, 10, 16)])
Predict

With a limit of 5 minutes instead of 12, what does cheapest_in_time return?

Pick one to see what it prints.
Pick an answer above to see the rest