Place a spiral-walking monkey on an infinite grid so every banana cell lies on its path, minimizing total steps walked.
Medium7GeometryImplementationSortingPrefix sumNo attempts yetTime limit1sMemory limit128 MBBananas are scattered over a grid of square cells that reaches without end in every direction. A monkey is dropped from a helicopter to pick them up. You put the monkey on one cell and point it in one of the four cardinal directions. It walks one cell forward, turns right, and then keeps moving so that its path forms a spiral.
The number of cells the monkey walks in a straight line grows as 1,1,2,2,3,3,4,4,…, and the monkey turns 90 degrees to the right after each straight stretch. The x coordinate grows to the right and the y coordinate grows upward. A monkey that starts facing up walks one cell up, turns right and walks one cell right, turns again and walks two cells down, turns again and walks two cells left, and so on.
The picture below shows the first part of the path when the monkey starts facing up.

The monkey picks up every banana on the cells it walks through. You cannot put it on a cell that holds a banana, because it would slip and crush the banana. You choose the starting cell and the starting direction. Find the smallest number of steps the monkey needs to pick up all bananas.
The first line holds the number of bananas N (1≤N≤100000).
Each of the next N lines holds the coordinates x and y of one banana, separated by a space. The coordinates are natural numbers smaller than 108. A cell holds at most one banana.
Print one natural number, the smallest number of steps needed to pick up all bananas.