Skip to content
BytePatterns

Shortest Paths With Rebate Roads

EasyGraphs#bellman-ford#negative-edges~20m

Problem

A region has n towns numbered 0 to n - 1 and one-way roads given as [u, v, cost]. Some roads pay a rebate, so their cost is negative, but no loop of roads has a negative total. Return the cheapest cost from town src to every town, using None for towns that cannot be reached.

Examples

Input:  n = 4, roads = [[0, 1, 4], [0, 2, 5], [2, 1, -3], [1, 3, 2]], src = 0
Output: [0, 2, 5, 4]
Why:    going 0 to 2 to 1 costs 5 - 3 = 2, cheaper than the direct road to 1 that costs 4
Input:  n = 3, roads = [[0, 1, -2]], src = 0
Output: [0, -2, None]
Why:    town 2 has no road leading into it
Input:  n = 1, roads = [], src = 0
Output: [0]
Why:    edge case, the start town costs nothing to reach

Hints

0 / 3

Stuck on the idea rather than the code? Bellman-Ford covers it.