Farmer John has constructed an obstacle course for the cows' enjoyment. The course consists of a sequence of N fences (1 <= N <= 50,000) of varying lengths, each parallel to the x axis. Fence i's y coordinate is i.
The door to FJ's barn is at the origin (marked '*' below). The starting point of the course lies at coordinate (S,N).
+-S-+-+-+ (fence #N)
+-+-+-+ (fence #N-1)
... ...
+-+-+-+ (fence #2)
+-+-+-+ (fence #1)
=|=|=|=*=|=|=| (barn)
-3-2-1 0 1 2 3
* Line 1: Two space-separated integers: N and S (-100,000 <= S <= 100,000)
* Lines 2..N+1: Each line contains two space-separated integers: A_i and B_i (-100,000 <= A_i < B_i <= 100,000), the starting and ending x-coordinates of fence segment i. Line 2 describes fence #1; line 3 describes fence #2; and so on. The starting position will satisfy A_N <= S <= B_N. Note that the fences will be traversed in reverse order of the input sequence.
* Line 1: The minimum distance back and forth in the x direction required to get from the starting point to the ending point by walking around the fences. The distance in the y direction is not counted, since it is always precisely N.
4 0 -2 1 -1 2 -3 0 -2 1
4
This problem has huge input data,use scanf() instead of cin to read data to avoid time limit exceed.
INPUT DETAILS:
Four segments like this:
+-+-S-+ Fence 4
+-+-+-+ Fence 3
+-+-+-+ Fence 2
+-+-+-+ Fence 1
|=|=|=*=|=|=| Barn
-3-2-1 0 1 2 3