Python coding

Cheapest drive with a limited tank

Cities are numbered 0 to n - 1, and fuel costs price[i] per unit in city i. Each entry of roads is [a, b, d]: a two-way road that burns d units of fuel. Your tank holds at most capacity units and is empty when you start at src. In any city you may buy any whole number of units that fits in the tank, and you may pass through a city more than once. Return the least money needed to reach dst, or -1 if it cannot be reached. If src == dst, the answer is 0.

1 ≤ n ≤ 20, 1 ≤ capacity ≤ 20; prices and d are positive integers. Two cities may be joined by more than one road.

  • cheapest_drive([3,1,9], [[0,1,5],[1,2,5]], 10, 0, 2) → 20
  • cheapest_drive([1,9,9], [[0,1,5],[1,2,5]], 10, 0, 2) → 10
  • cheapest_drive([1,9,9], [[0,1,5],[1,2,5]], 7, 0, 2) → 34
  • cheapest_drive([2,2], [[0,1,6]], 5, 0, 1) → -1
Ctrl/⌘ + Enter runs · Tab indents
Hint 1

The city alone is not enough state: arriving with more fuel can be worth more than arriving cheaper. Make each node a pair (city, fuel in tank).

Hint 2

Two kinds of edges. Buy one unit: (city, f) → (city, f + 1), costing price[city]. Drive a road with d ≤ f: (city, f) → (next, f − d), costing 0. Run Dijkstra on money spent.

Hint 3

Buying one unit at a time already covers every amount. Don't fill the tank at every stop, and don't buy just enough for the next road: both greedy rules lose on some map.

Solution and why it works
pythonO((n + E)·C·log(n·C)), E = len(roads), C = capacity · O((n + E)·C)
import heapq


def cheapest_drive(price: list[int], roads: list[list[int]], capacity: int, src: int, dst: int) -> int:
    adj = [[] for _ in price]
    for a, b, d in roads:
        adj[a].append((b, d))
        adj[b].append((a, d))
    spent = {(src, 0): 0}                # least money to be in a city with that much fuel
    heap = [(0, src, 0)]                 # (money spent, city, fuel in tank)
    while heap:
        cost, city, fuel = heapq.heappop(heap)
        if city == dst:
            return cost                  # first pop of dst, with any fuel left, is optimal
        if cost > spent[(city, fuel)]:
            continue                     # stale entry
        moves = [(cost, nxt, fuel - d) for nxt, d in adj[city] if d <= fuel]  # drive: free
        if fuel < capacity:
            moves.append((cost + price[city], city, fuel + 1))               # buy one unit
        for c, v, f in moves:
            if c < spent.get((v, f), float("inf")):
                spent[(v, f)] = c
                heapq.heappush(heap, (c, v, f))
    return -1

What you can do next depends on the fuel in the tank, so a node is (city, fuel): at most n·(capacity + 1) of them. Buying one unit costs price[city] and driving costs nothing, so no weight is negative and Dijkstra applies; the first time dst is popped, with any fuel left, is the answer. The trap is one best cost per city: a pricier arrival with more fuel can win later. Greedy rules (fill up, or buy only for the next road) fail too.