All problems

Problem 653

Minimum Number of Refueling Stops

Hard · 30 pts · Greedy, Heap, Dynamic Programming

Problem

A car drives east from position 0 to TARGET. It starts with STARTFUEL litres, uses one litre per mile, and has an unlimited tank. Gas stations along the way are given as (position, fuel); stopping at one adds all of its fuel. Find the fewest stops needed to reach TARGET, or -1 if it is impossible. Reaching a station or the target with exactly 0 fuel left is fine. Greedy: drive as far as possible, and when stuck, refuel at the largest station passed so far.

Input

The first line contains TARGET, STARTFUEL and S. Each of the next S lines contains a station's position and fuel, in increasing position order.

Output

Print the minimum number of stops, or -1.

Constraints

1 <= TARGET, STARTFUEL <= 10^9; 0 <= S <= 500; 0 < position < TARGET; positions strictly increasing; 1 <= fuel <= 10^9

Example input

100 10 4
10 60
20 30
30 30
60 40

Example output

2

Explanation

With TARGET = 100 and STARTFUEL = 10, drive to the station at 10 and take 60 litres (now 60), drive to the station at 60 and take 40 (now 40), and reach 100. Two stops are needed.

Every problem here can be used in a RelayTrixCode team match. Create a room.

Previous: Profitable Schemes Next: Count Different Palindromic Subsequences