Problem 500446 · easy · Phase 05 Advanced Algorithms & Graphs

Delivery Times From the Depot

graphs · Dijkstra · heap · weighted graph

A courier company serves n towns labelled 0 .. n-1. The road network is undirected and is given as a list roads where roads[i] = [u, v, minutes] means a road between towns u and v that takes minutes to drive (minutes >= 0). Two towns may be joined by several roads.

Return a list times of length n where times[i] is the shortest driving time from the town depot to town i. Use -1 for towns that cannot be reached; times[depot] is 0.

Examples

Input:  n = 5, roads = [[0,1,4],[0,2,1],[2,1,2],[1,3,5],[2,3,8]], depot = 0
Output: [0, 3, 1, 8, -1]
Explanation: 0 -> 2 -> 1 costs 1 + 2 = 3, cheaper than the direct road (4).
             Town 3 is reached via 0 -> 2 -> 1 -> 3 = 8. Town 4 has no roads.

Input:  n = 3, roads = [[0,1,7],[0,1,2],[1,2,0]], depot = 0
Output: [0, 2, 2]
Explanation: the cheaper of the two parallel roads is used; the last road is free.

Constraints

  • 1 <= n <= 5000, 0 <= len(roads) <= 10**4, 0 <= minutes <= 10**6
  • Target O(E log V) time.

Goals

  • Build a weighted adjacency list from an edge list
  • Run Dijkstra with a min-heap and skip stale heap entries
  • Report unreachable nodes with a sentinel
Starting Python…