import numpy as np
N=int(input())
x=[0 for i in range(N)]
y=[0 for i in range(N)]
for i in range(N):
  x[i],y[i]=map(int,input().split())
s=list(np.argsort(np.array(x)))
t=list(np.argsort(np.array(y)))
L=[]
R=[]
def norm(i,j):
  return min([abs(x[i]-x[j]),abs(y[i]-y[j])])
for i in range(N-1):
  L.append(norm(s[i],s[i+1]))
  R.append((s[i],s[i+1]))
  L.append(norm(t[i],t[i+1]))
  R.append((t[i],t[i+1]))
u=list(np.argsort(np.array(L)))
S=set()
M=0
for i in range(2*N-2):
  if not(set(R[u[i]])<=S):
    S.add(R[u[i]][0])
    S.add(R[u[i]][1])
    M+=L[u[i]]
print(M)
