Python coding

A toll loop that pays you

A toll network has n junctions numbered 0 to n - 1. Each entry of roads is [a, b, toll]: a one-way road from a to b that charges toll coins. A negative toll is a rebate: that road pays you. Return True if some loop of roads, starting and ending at the same junction, has tolls that add up to less than zero (a driver could repeat it forever and profit), otherwise False.

The loop may start at any junction. A road from a junction back to itself is a loop on its own, and the same two junctions may be joined by several roads.

Besides the tests, one large input (42 junctions, 16,384 loops) with a ~100 ms limit (scaled to your device's speed): brute force won't pass.

  • has_paying_loop(3, [[0,1,4],[1,2,-2],[2,0,-3]]) → true
  • has_paying_loop(3, [[0,1,4],[1,2,-2],[2,0,-2]]) → false
  • has_paying_loop(4, [[0,1,5],[2,3,-1],[3,2,0]]) → true
Ctrl/⌘ + Enter runs · Tab indents
Hint 1

Negative tolls rule out Dijkstra. Bellman-Ford relaxes every road in rounds; without a negative loop, every cost is final after n - 1 rounds.

Hint 2

The loop can be anywhere, even where junction 0 can't reach. Start every junction at cost 0, as if a free road led to each one.

Hint 3

Run up to n rounds. A round with no change means no paying loop; a change in round n means there is one.

Solution and why it works
pythonO(n·E), E = len(roads) · O(n)
def has_paying_loop(n: int, roads: list[list[int]]) -> bool:
    cost = [0] * n                       # as if a free road led to every junction
    for _ in range(n):                   # n - 1 rounds settle every cost, if no loop pays
        changed = False
        for a, b, toll in roads:
            if cost[a] + toll < cost[b]:
                cost[b] = cost[a] + toll
                changed = True
        if not changed:
            return False                 # settled early: nothing keeps getting cheaper
    return True                          # round n still improved: a negative loop

Without a negative loop, a cheapest route uses at most n - 1 roads, so n - 1 rounds of relaxing every road settle all costs and round n changes nothing. A negative loop keeps lowering the costs on it forever. Starting every junction at 0 finds a loop anywhere; running Bellman-Ford only from junction 0 misses one it cannot reach. A loop that sums to exactly 0 does not pay.