import bisect
from collections import deque
class UnionFind(): #Union-Find木の実装
    def __init__(self, n):
        self.n = n
        self.parents = [-1] * n
    def find(self, x):
        if self.parents[x] < 0:
            return x
        else:
            self.parents[x] = self.find(self.parents[x])
            return self.parents[x]
    def union(self, x, y):
        x = self.find(x)
        y = self.find(y)
        if x == y:
            return 0
        if self.parents[x] > self.parents[y]:
            x, y = y, x
        self.parents[x] += self.parents[y]
        self.parents[y] = x
        
N = int(input())
same = set()
xseq = []
yseq = []
edge = []
uf = UnionFind(N)
ans = 0

x,y = (int(x) for x in input().split())
same.add((x,y))
xseq.append((x,0))
yseq.append((y,0))
for i in range(1,N):
    x,y = (int(x) for x in input().split())
    if (x,y) not in same:
        same.add((x,y))
        xb = bisect.bisect_left(xseq,(x,i))
        xseq.insert(xb,(x,i))
        if xb == 0:
            edge.append((xseq[1][0]-x,(xseq[1][1],i)))
        elif xb == len(xseq)-1:
            edge.append((x-xseq[-2][0],(xseq[-2][1],i)))
        else:
            edge.append((xseq[xb+1][0]-x,(xseq[xb+1][1],i)))
            edge.append((x-xseq[xb-1][0],(xseq[xb-1][1],i)))
        yb = bisect.bisect_left(yseq,(y,i))
        yseq.insert(yb,(y,i))
        if yb == 0:
            edge.append((yseq[1][0]-y,(yseq[1][1],i)))
        elif yb == len(yseq)-1:
            edge.append((y-yseq[-2][0],(yseq[-2][1],i)))
        else:
            edge.append((yseq[yb+1][0]-y,(yseq[yb+1][1],i)))
            edge.append((y-yseq[yb-1][0],(yseq[yb-1][1],i)))
edge.sort()
d = deque(edge)
for i in range(len(d)):
    temp = d.popleft()
    if uf.find(temp[1][0]) != uf.find(temp[1][1]):
        uf.union(temp[1][0],temp[1][1])
        ans += temp[0]
    if uf.parents.count(-1*N) == 1:
        break
print(ans)