from heapq import heappop, heappush
import sys
input = sys.stdin.readline

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

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

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

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

class Kruskal:
    def __init__(self, Q, n):
        self.uf = UnionFind(n)
        self.cost = 0
        self.Q = Q
        for i in range(2 * N - 2):
            w, u, v = heappop(self.Q)
            if self.uf.same_check(u, v) != True:
                self.uf.union(u, v)
                self.cost += w

N = int(input())
L1 = []
L2 = []
for i in range(N):
    x, y = list(map(int, input().split()))
    L1.append([x, y, i + 1])
    L2.append([y, x, i + 1])
Lx = sorted(L1)
Ly = sorted(L2)
Q = []

for i in range(N - 1):
    u = Lx[i][2]
    v = Lx[i + 1][2]
    w = min(Lx[i+ 1][0] - Lx[i][0], abs(Lx[i + 1][1] - Lx[i][1]))
    heappush(Q, [w, u, v])
    u = Ly[i][2]
    v = Ly[i + 1][2]
    w = min(Ly[i+ 1][0] - Ly[i][0], abs(Ly[i + 1][1] - Ly[i][1]))
    heappush(Q, [w, u, v])

Km = Kruskal(Q, N)
print(Km.cost)

