D - Built? Editorial /

Time Limit: 2 sec / Memory Limit: 256 MB

配点 : 500500

問題文

平面上に、NN 個の街があります。ii 個目の街は、座標 (xi,yi)(x_i,y_i) にあります。同じ座標に、複数の街があるかもしれません。

座標 (a,b)(a,b) にある街と座標 (c,d)(c,d) にある街の間に道を造るのには、min(ac,bd)min(|a-c|,|b-d|) 円かかります。街と街の間以外に、道を造ることはできません。

任意の 22 つの街の間を、道を何本か通って行き来できるようにするためは、最低で何円必要でしょうか。

制約

  • 2N1052 ≦ N ≦ 10^5
  • 0xi,yi1090 ≦ x_i,y_i ≦ 10^9
  • 入力は全て整数である

入力

入力は以下の形式で標準入力から与えられる。

NN
x1x_1 y1y_1
x2x_2 y2y_2
:
xNx_N yNy_N

出力

任意の 22 つの街の間を道を何本か通って行き来できるようにするためにかかるお金の最小値を出力せよ。


入力例 1Copy

Copy
3
1 5
3 9
7 8

出力例 1Copy

Copy
3

1122 、街 2233 の間に道を造ると、かかるお金は 2+1=32+1=3 円になります。


入力例 2Copy

Copy
6
8 3
4 9
12 19
18 1
13 5
7 6

出力例 2Copy

Copy
8

Score : 500500 points

Problem Statement

There are NN towns on a plane. The ii-th town is located at the coordinates (xi,yi)(x_i,y_i). There may be more than one town at the same coordinates.

You can build a road between two towns at coordinates (a,b)(a,b) and (c,d)(c,d) for a cost of min(ac,bd)min(|a-c|,|b-d|) yen (the currency of Japan). It is not possible to build other types of roads.

Your objective is to build roads so that it will be possible to travel between every pair of towns by traversing roads. At least how much money is necessary to achieve this?

Constraints

  • 2N1052 ≤ N ≤ 10^5
  • 0xi,yi1090 ≤ x_i,y_i ≤ 10^9
  • All input values are integers.

Input

Input is given from Standard Input in the following format:

NN
x1x_1 y1y_1
x2x_2 y2y_2
:
xNx_N yNy_N

Output

Print the minimum necessary amount of money in order to build roads so that it will be possible to travel between every pair of towns by traversing roads.


Sample Input 1Copy

Copy
3
1 5
3 9
7 8

Sample Output 1Copy

Copy
3

Build a road between Towns 11 and 22, and another between Towns 22 and 33. The total cost is 2+1=32+1=3 yen.


Sample Input 2Copy

Copy
6
8 3
4 9
12 19
18 1
13 5
7 6

Sample Output 2Copy

Copy
8


2025-04-25 (Fri)
10:02:00 +00:00