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(1,n):
    t.append([x[i-1][2],x[i][2],x[i][0]-x[i-1][0]])
    t.append([y[i-1][2],y[i][2],y[i][1]-y[i-1][1]])
t=sorted(t,key=lambda x:x[2])
d=[i for i in range(n+1)]
p=[1]*(n+1)
def f(x):
    if x==d[x]:
        return x
    x=d[x]
    return f(d[x])
r=0
for a,b,c in t:
    a=f(a)
    b=f(b)
    if a!=b:
        if p[a]<p[b]:
            d[b]=a
            p[b]+=p[a]
            r+=c
        else:
            d[a]=b
            p[a]+=p[b]
            r+=c
print(r)