def getlist():
	return list(map(int, input().split()))

from heapq import heappop, heappush

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
        while self.Q:
            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())
X = []
Y = []
for i in range(N):
	x, y = getlist()
	X.append([x, i])
	Y.append([y, i])

X = sorted(X)
Y = sorted(Y)

#辺追加
Q = []
for i in range(N - 1):
	w, a, b = X[i + 1][0] - X[i][0], X[i][1], X[i + 1][1]
	heappush(Q, [w, a, b])
	w, a, b = Y[i + 1][0] - Y[i][0], Y[i][1], Y[i + 1][1]
	heappush(Q, [w, a, b])

#全域木
Km = Kruskal(Q, N)
print(Km.cost)