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
FJ's original intention was for the cows to jump over the fences, but cows are much more comfortable keeping all four hooves on the ground. Thus, they will walk along the fence and, when the fence ends, they will turn towards the x axis and continue walking in a straight line until they hit another fence segment or the side of the barn. Then they decide to go left or right until they reach the end of the fence segment, and so on, until they finally reach the side of the barn and then, potentially after a short walk, the ending point.
Naturally, the cows want to walk as little as possible. Find the minimum distance the cows have to travel back and forth to get from the starting point to the door of the barn.