from heapq import *
n=int(input())
s=[]
for i in range(n):
    s.append(list(map(int,input().split()))+[i])
x=sorted(s,key=lambda x:x[0])
y=sorted(s,key=lambda x:x[1])
t=[[]for i in range(n)]
for i in range(1,n):
    t[x[i-1][2]].append([x[i][0]-x[i-1][0],x[i][2]])
    t[x[i][2]].append([x[i][0]-x[i-1][0],x[i-1][2]])
    t[y[i-1][2]].append([y[i][1]-y[i-1][1],y[i][2]])
    t[y[i][2]].append([y[i][1]-y[i-1][1],y[i-1][2]])
s=[True]*n
s[0]=False
a=0
h=t[0]
heapify(h)
while h:
    p,q=heappop(h)
    if s[q]:
        s[q]=False
        a+=p
        for i,j in t[q]:
            if s[j]:
                heappush(h,[i,j])
print(a)