Problem:
Score : 500 points

Problem Statement

There are N towns on a plane. The i-th town is located at the coordinates (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) and (c,d) for a cost of 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

2 ≤ N ≤ 10^5

0 ≤ x_i,y_i ≤ 10^9

All input values are integers.

Input

Input is given from Standard Input in the following format:

N
x_1 y_1
x_2 y_2
:
x_N y_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 1

3
1 5
3 9
7 8

Sample Output 1

3

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

Sample Input 2

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

Sample Output 2

8

Solution in Python (3.4.3) (judge verdict: Accepted)

class UnionFind:
    def __init__(self, n):
        self.parent = [i for i in range(n + 1)]
        self.rank = [0 for _ in range(n + 1)]
        self.size = [1] * (n + 1)

    def find(self, x):
        if self.parent[x] == x:
            return x
        else:
            self.parent[x] = self.find(self.parent[x])
            return self.parent[x]

    def union(self, x, y):
        x = self.find(x)
        y = self.find(y)
        if x == y:
            return
        if self.rank[x] < self.rank[y]:
            self.parent[x] = y
            self.size[y] += self.size[x]
        else:
            self.parent[y] = x
            self.size[x] += self.size[y]
            if self.rank[x] == self.rank[y]:
                self.rank[x] += 1

    def check_same(self, x, y):
        return self.find(x) == self.find(y)

    def get_size(self, x):
        return self.size[self.find(x)]


N = int(input())
ixy = []
for i in range(N):
    x, y = tuple(map(int, input().split()))
    ixy.append((i + 1, x, y))

x_order = sorted(ixy, key=lambda x: x[1])
y_order = sorted(ixy, key=lambda x: x[2])

edge = []

for i in range(1, N):
    pre_i1, pre_x1, pre_y1 = x_order[i - 1]
    i1, x1, y1 = x_order[i]
    edge.append((x1 - pre_x1, pre_i1, i1))
    pre_i2, pre_x2, pre_y2 = y_order[i - 1]
    i2, x2, y2 = y_order[i]
    edge.append((y2 - pre_y2, pre_i2, i2))

edge = sorted(edge, key=lambda x: x[0])
union_find = UnionFind(N)
ans = 0
for e in edge:
    cost, pre_i, i = e
    if union_find.check_same(pre_i, i):
        continue
    else:
        union_find.union(pre_i, i)
        ans += cost
print(ans)