import sequtils,strutils,algorithm
type
    coordinate = tuple[x:int64,y:int64,ID : int]
    towncost = tuple[ID : int,cost : int64]
var
    i,j,minx,miny,ans : int64
    N,flag,M,m,n,cnt : int
    L : seq[int64]
    town : coordinate
    Towns = newSeq[coordinate](0)
    xTowns,yTowns : seq[coordinate]
N = stdin.readline.parseInt
var
    Bound = newSeqWith(N,newSeq[towncost](0))
type
    townQue = seq[towncost]
proc append(A:var townQue, b:towncost)=
    M = A.len
    m = 0
    while M - m > 0:
        n = (M + m) div 2
        if A[n].cost == b.cost:
            M = n
            m = n
            break
        elif A[n].cost < b.cost:
            M = n
        elif A[n].cost > b.cost:
            m = n + 1
    if m == A.len:
        A.add(b)
    else:
        A = A[0..n-1] & b & A[n..high(A)]
proc pop(A: var townQue): towncost =
    result = A[high(A)]
    A.delete(high(A))
for n in 0..<N:
    L = stdin.readline.split.map(parseBiggestInt)
    town = (L[0],L[1],n)
    Towns.add(town)
xTowns = Towns.sortedByIt(it.x)
yTowns = Towns.sortedByIt(it.y)
var town2 : towncost
for i,t in xTowns:
    if i == 0:
        town2.cost = xTowns[i + 1].x - t.x
        town2.ID = xTowns[i + 1].ID
    elif i == N - 1:
        town2.cost = t.x - xTowns[i - 1].x
        town2.ID = xTowns[i - 1].ID
    else:
        town2.cost = xTowns[i + 1].x - t.x
        town2.ID = xTowns[i + 1].ID
        Bound[t.ID].add(town2)
        town2.cost = t.x - xTowns[i - 1].x
        town2.ID = xTowns[i - 1].ID
    Bound[t.ID].add(town2)
for i,t in yTowns:
    if i == 0:
        town2.cost = yTowns[i + 1].y - t.y
        town2.ID = yTowns[i + 1].ID
    elif i == N - 1:
        town2.cost = t.y - yTowns[i - 1].y
        town2.ID = yTowns[i - 1].ID
    else:
        town2.cost = yTowns[i + 1].y - t.y
        town2.ID = yTowns[i + 1].ID
        Bound[t.ID].add(town2)
        town2.cost = t.y - yTowns[i - 1].y
        town2.ID = yTowns[i - 1].ID
    Bound[t.ID].add(town2)
cnt = 1
ans = 0
var boundTown = newSeqWith(N,false)
boundTown[0] = true
var TQ : townQue
TQ = @[]
for t in Bound[0]:
    TQ.append(t)
while cnt < N:
    town2 = TQ.pop()
    if boundTown[town2.ID] == true:
        continue
    boundTown[town2.ID] = true
    cnt += 1
    ans += town2.cost
    for t in Bound[town2.ID]:
        if not boundTown[t.ID]:
            TQ.append(t)
echo ans