import sys

stdin = sys.stdin

ns = lambda: stdin.readline()
ni = lambda: int(ns())
na = lambda: list(map(int, stdin.readline().split()))

class UnionFind:
    def __init__(self, size):
        self.table = [-1 for _ in range(size)]

    def find(self, x):
        if self.table[x] < 0:
            return x
        else:
            self.table[x] = self.find(self.table[x])
            return self.table[x]

    def union(self, x, y):
        s1 = self.find(x)
        s2 = self.find(y)
        if s1 != s2:
            if self.table[s1] <= self.table[s2]:
                self.table[s1] += self.table[s2]
                self.table[s2] = s1
            else:
                self.table[s1] = s2
                self.table[s2] += self.table[s1]
            return True
        return False

N = ni()
a = []
b = []
for i in range(N):
    x, y = na()
    a.append((x, i))
    b.append((y, i))

a.sort()
b.sort()
t = []
for i in range(1, N):
    t.append((a[i][0]-a[i-1][0], a[i][1], a[i-1][1]))
    t.append((b[i][0]-b[i-1][0], b[i][1], b[i-1][1]))

t.sort()
ans = 0
uf = UnionFind(N)
for c, d, e in t:
    if uf.union(d,e):
        ans += c

print(ans)
    