Problem 442281 · hard · Level 04 Non-Linear Data Structures

Fuel Barges on the Long Canal

heaps · greedy · max-heap · retroactive choice

A narrowboat travels along a straight canal from position 0 to position target. It sets off with fuel litres and uses one litre per unit of distance. Fuel barges are moored along the way, listed in stations as [position, litres] in increasing position order, all before target; tying up at a barge adds all of its litres to the tank (the tank never fills up). The boat can only tie up at a barge it actually reaches, and arriving anywhere with exactly zero fuel left is fine.

Return the fewest barge stops that get the boat to target, or -1 if it cannot get there.

Examples

Input:  target = 120, fuel = 20, stations = [[15, 25], [40, 30], [60, 50], [95, 20]]
Output: 3
Explanation: stop at 15 (fuel reaches 45 from position 0), stop at 40 (75), stop at 60 (125),
             which is enough to reach 120. No two stops suffice.

Input:  target = 50, fuel = 50, stations = []
Output: 0

Input:  target = 80, fuel = 6, stations = [[9, 200]]
Output: -1
Explanation: the only barge is at position 9, beyond the 6 units the starting fuel covers.

Constraints

  • 1 <= target <= 10**9, 0 <= fuel <= 10**9, 0 <= len(stations) <= 10**5
  • 0 < position < target, 1 <= litres <= 10**9
  • Target complexity: O(n log n).

Goals

  • Postpone decisions: collect passed stations and refuel from them only when stuck
  • Always refuel from the best station passed so far
  • Detect impossibility when no passed station remains
Starting Python…