from heapq import *
n=int(input())
s=[]
for i in range(n):
    a,b=map(int,input().split())
    s.append([a,b,i])
x=sorted(s)
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=[1]*n
s[0],h=0,[]
a=0
for i in t[0]:
    heappush(h,i)
while h:
    p,q=heappop(h)
    if s[q]:
        s[q]=0
        a+=p
        for i in t[q]:
            heappush(h,i)
print(a)