Fuel Economy
InterviewTime limit1sMemory limit128 MB
Find the cheapest way to buy fuel along a route with a tank of capacity G, visiting stations with given prices, or report that the trip is impossible.
Problem
A driver is setting out on a long road trip. The truck has a fuel tank that can hold at most units of fuel (). The truck gets poor mileage: it burns exactly one unit of fuel for every unit of distance traveled, and the whole trip is units of distance long ().
Because the tank may need to be refilled several times along the way, the driver lists all fuel stations on the route (). Station sits at distance from the start () and sells fuel at a price of per unit ().
The truck begins the trip with exactly units of fuel already in the tank (). Determine the minimum total amount of money that must be spent on fuel to reach the destination at distance . If reaching the destination is impossible, output instead.
Note: the answer may not fit in a signed -bit integer.
Input
- Line : four space-separated integers , , , and .
- Lines : line contains two integers and , the position and per-unit price of station .
Output
- One line: the minimum cost to reach the destination, or if the destination cannot be reached.
Hint
In the first case the route runs from position to . The truck starts with units of fuel in a tank of capacity , and there are stations.
One optimal plan: drive units to the station at position and buy units there (cost ) to reach the station at position ; fill the tank completely there (cost ); at position buy more units (cost ). The total cost is .
A greedy strategy works: at each station, if a cheaper station lies within one full tank's range, buy only enough fuel to reach it; otherwise fill the tank completely and continue to the cheapest reachable station.