Under construction

Still being built. Things may change

Taxi

Time limit1sMemory limit128 MB

Summary
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 MM (1≤M≤1091 \le M \le 10^9). 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 NN cows (1≤N≤1051 \le N \le 10^5), 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 00, and must finish her journey at the rightmost point, position MM.

Input

  • Line 1: Two space-separated integers NN and MM.
  • Lines 2 to N+1N+1: Line i+1i+1 contains two space-separated integers sis_i and tit_i (0≤si,ti≤M0 \le s_i, t_i \le M), the starting position and destination of the ii-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 ∑i∣si−ti∣\sum_i |s_i - t_i|. 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 {0}∪{ti}\{0\} \cup \{t_i\}, and the set of points where one can end is {si}∪{M}\{s_i\} \cup \{M\}; sorting both sets and pairing them in order minimizes the total empty distance.

Examples3

  1. Example 1

    Input
    2 10
    0 9
    6 5
    
    Expected output
    12
    
  2. Example 2

    Input
    1 5
    0 5
    
    Expected output
    5
    
  3. Example 3

    Input
    1 10
    8 2
    
    Expected output
    22