Lv.3floyd-warshallgraphshortest-path
All-Pairs Travel Time
- Memory limit
- 256 MB
- Correctness time limit
- 10000 ms
- Solvers
- 0
There are n cities numbered 0 to n - 1. roads[i] = [a, b, t] is a one-way road from city a to city b
taking t minutes.
For each queries[j] = [a, b], find the shortest travel time from a to b and return the answers in query order. Use
-1 when b cannot be reached and 0 when a = b.
Examples
| n | roads | queries | result |
|---|---|---|---|
4 | [[0, 1, 5], [1, 2, 2], [0, 2, 9], [2, 3, 1]] | [[0, 2], [0, 3], [3, 0], [1, 1]] | [7, 8, -1, 0] |
3 | [[0, 1, 4], [1, 0, 1], [0, 1, 2]] | [[1, 0], [0, 1], [2, 1]] | [1, 2, -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[][], queries: int[][]) → int[]
Constraints
-
n -
roads.length,a,b,t; parallel roads anda = bmay appear -
queries.length
Expected complexity
- Time
- O(n^3 + Q)
- Space
- O(n^2)
Examples
| n | roads | queries | Expected |
|---|---|---|---|
4 | [[0,1,5],[1,2,2],[0,2,9],[2,3,1]] | [[0,2],[0,3],[3,0],[1,1]] | [7,8,-1,0] |
3 | [[0,1,4],[1,0,1],[0,1,2]] | [[1,0],[0,1],[2,1]] | [1,2,-1] |
Hint
Hint
With only 200 cities, precompute every pair once with Floyd–Warshall (k as the outermost loop,
d[i][j] = min(d[i][j], d[i][k] + d[k][j]), keeping the shortest of parallel roads) and answer each query by lookup.
Running Dijkstra per query is and exceeds the time limit.
Time limits per language
| Language | Efficiency time limit | |
|---|---|---|
| C (GCC, gnu17) | 200 ms | estimated |
| C++ (GCC, gnu++23) | 200 ms | derived |
| Python 3.13 | 1000 ms | derived |
| Java 25 | 1332 ms | derived |
| Kotlin 2.4 (JVM) | 1400 ms | estimated |
| C# 14 (.NET 10) | 1400 ms | estimated |
Test groups
| Group | Weight | Tests | Visibility |
|---|---|---|---|
| sample | 0 | 2 | inputs and outputs |
| correctness | 40 | 10 | verdict only |
| performance | 60 | 4 | verdict only |