Polski

Shortest delivery times (Dijkstra)

A network of logistics hubs with one-way routes of different travel times. Compute the shortest travel time from the warehouse to every hub – Dijkstra's algorithm with a heap that some languages make you write yourself.

hard · typescript · javascript · python · csharp · java · go · 40 XP

A courier company has n hubs (numbered 0 … n-1) and one-way routes between them. A route [from, to, minutes] means travelling from from to to takes minutes minutes. The dispatcher wants to know how fast a parcel from warehouse source can reach every hub.

Task

Return an array of length n whose element i is the shortest total travel time from source to hub i, or -1 when the hub is unreachable. The distance to source is 0.

  • Routes are directed, may repeat (the cheapest counts) and may lead from a hub back to itself.
  • Times are non-negative (0 included).
  • Sums of times can exceed the 32-bit int range – in C# and Java the result is long[].

Signatures: shortestDistances(n, edges, source) (JS/TS), shortest_distances(n, edges, source) (Python), Solution.ShortestDistances (C#, long[]), Solution.shortestDistances (Java, long[]), ShortestDistances (Go, []int).

Examples

nedgessourceResult
4[[0,1,4], [0,2,1], [2,1,2], [1,3,1], [2,3,5]]0[0, 3, 1, 4]
4[[0,3,10], [0,1,1], [1,2,1], [2,3,1]]0[0, 1, 2, 3] – more hops, less time
3[[1,0,5], [0,2,7]]0[0, -1, 7] – routes are one-way

Constraints

  • 1 ≤ n ≤ 100,000, up to 200,000 routes, 0 ≤ minutes ≤ 10⁶.

Expected complexity

O((V + E) log V) time, O(V + E) memory.