Funcia
Lv.3dijkstragraphheapshortest-path

Fastest Delivery Routes

Memory limit
256 MB
Correctness time limit
10000 ms
Solvers
0
0

There are n towns 0..n-1; the warehouse is in town start. roads[i] = [a, b, t] is a two-way road taking t minutes. Return an array whose i-th element is the shortest travel time from start to town i (-1 if unreachable, 0 for start).

Examples

nroadsstartresult
4[[0, 1, 4], [0, 2, 1], [2, 1, 2], [1, 3, 5]]0[0, 3, 1, 8]
3[[0, 1, 7]]1[7, 0, -1]

Efficiency

This problem has performance tests. Judge the required time complexity from the input sizes in the constraints.

Function signature

solution(n: int, roads: int[][], start: int) → long[]

Constraints

  • 1≤1 \le n ≤100,000\le 100{,}000, 0≤0 \le start <n< n, 0≤0 \le roads.length ≤200,000\le 200{,}000
  • 0≤a,b<n0 \le a, b < n, 1≤t≤1061 \le t \le 10^6; parallel roads and self-loops may appear. Distances can exceed 32 bits.

Expected complexity

Time
O((N + M) log N)
Space
O(N + M)

Examples

nroadsstartExpected
4[[0,1,4],[0,2,1],[2,1,2],[1,3,5]]0[0,3,1,8]
3[[0,1,7]]1[7,0,-1]

Hint

Hint

Dijkstra with a min-heap: pop the closest (d, u), skip stale entries with d > dist[u], relax neighbours. Use 64-bit distances. Scanning all towns for the closest unsettled one is O(N2)O(N^2) and exceeds the time limit.

Time limits per language

LanguageEfficiency time limit
C (GCC, gnu17)292 msestimated
C++ (GCC, gnu++23)292 msderived
Python 3.131000 msderived
Java 251816 msderived
Kotlin 2.4 (JVM)1584 msestimated
C# 14 (.NET 10)1584 msestimated

Test groups

GroupWeightTestsVisibility
sample02inputs and outputs
correctness409verdict only
performance604verdict only
Loading editor…
Log in to run or submit code.

No result yet. Run or submit your code.