#P3076. [USACO13FEB] Taxi G

[USACO13FEB] Taxi G

Description

Bessie runs a taxi service for the other cows along a fence of length MM (1M1091 \le M \le 10^9). There are NN cows (1N1051 \le N \le 10^5). Cow ii starts at position aia_i and wants to go to position bib_i (0ai,biM0 \le a_i, b_i \le M). Bessie starts at the leftmost point, position 00, must finish at the rightmost point, position MM, and wants to minimize the total distance she drives.

Bessie’s car can carry only one cow at a time. Cows can enter and exit the car instantaneously. To save gas, Bessie may drop a cow off at an intermediate position before reaching that cow’s destination.

Determine the minimum total distance Bessie must drive to complete all rides and end at position MM.

Input Format

  • Line 1: NN and MM separated by a space.
  • Lines 2..1+N2..1+N: The (i+1)(i+1)‑th line contains two space‑separated integers, s_is\_i and t_it\_i (0s_i,t_iM0 \le s\_i, t\_i \le M), indicating the starting position and destination position of the ii‑th cow.

Output Format

  • Line 1: A single integer indicating the total amount of driving Bessie must do. Note that the result may not fit into a 32‑bit integer.
2 10 
0 9 
6 5 

12 

Hint

There are two cows waiting along a fence of length 1010. The first cow wants to go from position 00 (where Bessie starts) to position 99. The second cow wishes to go from position 66 to position 55.

Bessie picks up the first cow at position 00 and drives to position 66. There she drops off the first cow, delivers the second cow to her destination, and returns to pick up the first cow. She then drops off the first cow and drives the rest of the way to position 1010.

Translated by ChatGPT 5