#P9624. Railgun Robot Termination
Railgun Robot Termination
Railgun Robot Termination
In Academy City, there are n evil robots at positions \( (x_i, y_i) \) for \(1 \le i \le n\). Misaka Mikoto, also known as Railgun, starts at \( (0,0) \) and can eliminate any robot that shares the same \(x\)-coordinate or \(y\)-coordinate as her current location. When Misaka is at \( (x_m, y_m) \), all robots with \( x_i=x_m \) or \( y_i=y_m \) are terminated.
Misaka only travels between integer points along the grid (moving horizontally or vertically). She wishes to plan a route so that, by visiting a set of integer points, every robot is eliminated because for every robot \( (x_i,y_i) \), at least one of the following holds: \[ x_i = x_m \quad \text{or} \quad y_i = y_m \] for some point \( (x_m,y_m) \) that she visits. The cost of a route is measured by the Manhattan distance travelled.
Your task is to help Misaka calculate the minimum total distance she has to move so that all robots are eliminated.
Note: Although Misaka moves in steps between adjacent integer points, you may assume that if she needs to cover any continuous interval \([L,R]\) on one axis, the minimal distance needed is given by \[ D(L,R)=\begin{cases} R-0, & \text{if }0\le L,\\ 0-L, & \text{if }R\le 0,\\ (R-L)+\min(R, -L), & \text{if }L<0< R. \end{cases} \]
The strategy involves choosing some set of \(x\)-coordinates to visit and some set of \(y\)-coordinates to visit such that for every robot \( (x_i,y_i) \), at least one of \( x_i \) or \( y_i \) is included in the visited coordinates. The total cost is the sum of the minimum costs required to cover the chosen \(x\)-coordinates and \(y\)-coordinates (each computed as the cost of covering an interval on that axis).
It is guaranteed that an optimal route exists with the chosen points covering continuous intervals on each axis.
inputFormat
The first line contains an integer \(n\) (\(1\le n\le 10^5\)) -- the number of robots in Academy City.
Each of the next \(n\) lines contains two integers \(x_i\) and \(y_i\) (\(|x_i|, |y_i| \le 10^9\)), representing the position of a robot.
outputFormat
Output a single integer -- the minimum Manhattan distance Misaka must travel to eliminate all the robots.
sample
3
0 5
-3 0
2 -1
7