Taxi
Time limit1sMemory limit128 MB
Bessie drives one cow at a time along a fence of length M, may drop cows short of their goals, starts at 0 and ends at M; find the minimum total driving distance.
- Level
Hard8 of 10
- Topics
- Greedy, Sorting, Math, Implementation
- Solved
- No attempts yet
Problem
Bessie is running a taxi service for the other cows on the farm. The cows have gathered at different locations along a fence of length (). They have grown bored with their current spots and each wishes to move somewhere else along the fence. Bessie must pick up each cow at its starting position and drive it to its destination.
Bessie's car is small, so she can transport only one cow at a time. Cows can enter and exit the car instantaneously.
To save gas, Bessie wants to minimize the total distance she drives. Given the starting and ending positions of each of the cows (), determine the least amount of driving Bessie has to do. To save the most gas, she may occasionally need to drop a cow off at a position other than its destination.
Bessie starts at the leftmost point of the fence, position , and must finish her journey at the rightmost point, position .
Input
- Line 1: Two space-separated integers and .
- Lines 2 to : Line contains two space-separated integers and (), the starting position and destination of the -th cow.
Output
- Line 1: A single integer, the minimum total distance Bessie must drive. Note that the result may not fit in a 32-bit integer.
Hint
It helps to notice that Bessie does not have to drive each cow straight to its destination. By dropping a cow at an intermediate point and picking it up later, she can sometimes shorten the distance she spends driving with an empty car.
The total distance splits into two parts. First, moving each cow from its start to its destination always costs . Second, there is the empty driving needed to reposition between one drop-off and the next pick-up. The set of points where an empty trip can begin is , and the set of points where one can end is ; sorting both sets and pairing them in order minimizes the total empty distance.