Shortest Distance After Road Addition Queries II - Problem
You are given an integer n and a 2D integer array queries. There are n cities numbered from 0 to n - 1.
Initially, there is a unidirectional road from city i to city i + 1 for all 0 <= i < n - 1.
queries[i] = [u_i, v_i] represents the addition of a new unidirectional road from city u_i to city v_i.
After each query, you need to find the length of the shortest path from city 0 to city n - 1.
There are no two queries such that queries[i][0] < queries[j][0] < queries[i][1] < queries[j][1].
Return an array answer where for each i in the range [0, queries.length - 1], answer[i] is the length of the shortest path from city 0 to city n - 1 after processing the first i + 1 queries.
Input & Output
Example 1 — Basic Road Addition
$
Input:
n = 5, queries = [[0,3]]
›
Output:
[2]
💡 Note:
Initially: 0→1→2→3→4 (distance 4). After adding road 0→3: shortest path becomes 0→3→4 (distance 2).
Example 2 — Multiple Queries
$
Input:
n = 4, queries = [[0,2],[1,3]]
›
Output:
[2,1]
💡 Note:
Initially: 0→1→2→3 (distance 3). After [0,2]: 0→2→3 (distance 2). After [1,3]: 0→2 and optimal becomes 0→2 then skip to 3 via any path giving distance 1.
Example 3 — No Improvement
$
Input:
n = 3, queries = [[1,2]]
›
Output:
[2]
💡 Note:
Initially: 0→1→2 (distance 2). Adding road 1→2 doesn't create a shortcut from 0 to 2, so distance remains 2.
Constraints
- 3 ≤ n ≤ 105
- 1 ≤ queries.length ≤ 105
- queries[i].length = 2
- 0 ≤ ui < vi < n
- There are no repeated queries
Visualization
Tap to expand
Understanding the Visualization
1
Initial Network
Cities connected sequentially: 0→1→2→3→4
2
Add Shortcuts
New roads create express routes skipping cities
3
Calculate Distance
Find shortest path length after each addition
Key Takeaway
🎯 Key Insight: New roads create express lanes that skip intermediate cities, reducing the shortest path distance by eliminating unnecessary stops.
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code