#P10964. Minimum Walking Distance on a Fence Obstacle Course

    ID: 13013 Type: Default 1000ms 256MiB

Minimum Walking Distance on a Fence Obstacle Course

Minimum Walking Distance on a Fence Obstacle Course

Farmer John has constructed an obstacle course for the cows. The course consists of a sequence of N fences (with 1\le N\le 100000), where fence i is located at y=i and spans horizontally from L_i to R_i. The barn door is at the origin, i.e. at (0,0). The cows start the course on fence N at the point (S,N), where it is guaranteed that L_N\le S\le R_N.

Since cows are more comfortable walking than jumping, they adopt the following strategy:

  • While on a fence, they may walk left or right to reach one of its endpoints.
  • When they reach an endpoint, they leave the fence and walk vertically downward (towards the x-axis) until they hit the next fence. In particular, if a cow leaves fence i at some point x, she will fall vertically until she reaches the first fence below (with index j, where j<i) such that L_j \le x \le R_j. If no such fence exists, the cow continues down to the barn (at y=0).
  • Once the cow lands on a fence, her horizontal position remains unchanged. She can then walk along that fence to reach one of its endpoints and repeat the process.
  • After leaving the lowest fence (fence 1), the cow may have to walk a short horizontal distance along the barn wall to reach the door at (0,0).

The total distance traveled is the sum of horizontal distances (while walking along fences or the barn wall) and vertical distances (when falling between fences or to the barn). Find the minimum total distance the cow must travel to get from the start to the barn door.

Note: All formulas are expressed in \( \LaTeX \) format. For example, the condition for the fence coordinates is given by:

[ L_N \le S \le R_N ]

inputFormat

The first line contains two integers N and S.

Each of the following N lines contains two integers Li and Ri, which represent the left and right x-coordinates of the fence at y=i. It is guaranteed that LN \le S \le RN.

outputFormat

Output a single integer: the minimum walking distance required for the cow to reach the barn door at (0,0).

sample

3 5
3 7
2 6
4 8
8