Time limit
2s
Memory limit
128 MB
Jimin must escape from Jungmoon by moving downward to an exit. There are N fences parallel to the x-axis, and the i-th fence is located at y=i. The fences are too high to climb over. If Jimin's current x-coordinate lies inside a fence segment, he must move horizontally to the left end or the right end of that fence before he can continue moving downward.
In the diagram below, S marks the starting x-coordinate, and * marks the exit after all fences have been passed. The exit has x-coordinate 0.
+-+-S-+ 4th fence +-+-+-+ 3rd fence +-+-+-+ 2nd fence +-+-+-+ 1st fence |=|=|=*=|=|=|-3-2-1 0 1 2 3One possible path in the diagram first moves 1 unit in the positive x direction to reach the end of the 4th fence, then moves downward. It then reaches the 2nd fence, moves 1 more unit in the positive x direction to reach that fence's end, descends again, and finally moves 2 units in the negative x direction to the exit. Vertical movement has the same total length for every valid path, so it is not counted. The total horizontal distance of this path is 4, and it is shortest for the diagram.
Given the x-coordinate interval of every fence, find the minimum horizontal distance needed to reach the exit.
The first line contains the number of fences N (1 <= N <= 50,000) and Jimin's starting x-coordinate S (-100,000 <= S <= 100,000), separated by a space.
Each of the next N lines contains the two endpoint x-coordinates of one fence segment. The i-th fence in input order is located at y=i. Every x-coordinate is between -100,000 and 100,000, inclusive.
Print the minimum horizontal distance required to reach the exit.
+-+-S-+ 4th fence +-+-+-+ 3rd fence +-+-+-+ 2nd fence +-+-+-+ 1st fence |=|=|=*=|=|=|-3-2-1 0 1 2 3