class UnionFind:

    def __init__(self, size):
        # 負の値はルート (集合の代表) で集合の個数
        # 正の値は次の要素を表す
        self.size = size
        self.table = [-1 for _ in range(size)]

    def find(self, x):
        # 集合の代表を求める
        while self.table[x] >= 0:
            if self.table[self.table[x]] >= 0:
                self.table[x] = self.table[self.table[x]]
            x = self.table[x]
        return 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[s2] += self.table[s1]
                self.table[s1] = s2
        return self.table[s1]


n = int(input())
uf = UnionFind(n+1)
p = []
q = []
for i in range(n):
    x,y = map(int, input().split())
    p.append((x, y, i))
    q.append((y, x, i))

p.sort()
q.sort()

total = 0
x = 0
y = 0
while x<n-1 and y<n-1:
    while x < n-1 and uf.find(p[x][2]) == uf.find(p[x+1][2]):
        x += 1
    while y < n-1 and uf.find(p[y][2]) == uf.find(p[y+1][2]):
        y += 1
    if x+1 >= n or y+1 >= n:
        break
    if min(abs(p[x+1][0] - p[x][0]), abs(p[x+1][1] - p[x][1])) < min(abs(q[y+1][0] - q[y][0]), abs(q[y+1][1] - q[y][1])):
        total += min(abs(p[x+1][0] - p[x][0]), abs(p[x+1][1] - p[x][1]))
        uf.union(p[x+1][2], p[x][2])
        x += 1
    else:
        total += min(abs(q[y+1][0] - q[y][0]), abs(q[y+1][1] - q[y][1]))
        uf.union(q[y+1][2], q[y][2])
        y += 1
print(total)