from copy import deepcopy
import heapq
N = int(input())
T = [None for i in range(N)]
for i in range(N):
    x, y = map(int, input().split())
    T[i] = (x, y, i)
Tx, Ty = deepcopy(T), deepcopy(T)
Tx.sort()
Ty.sort(key = lambda x:x[1])

Edge = [[] for i in range(N)]
for i in range(N-1):
    Edge[Tx[i][2]].append((abs(Tx[i][0]-Tx[i+1][0]), Tx[i+1][2]))
    Edge[Tx[i+1][2]].append((abs(Tx[i][0]-Tx[i+1][0]), Tx[i][2]))
    Edge[Ty[i][2]].append((abs(Ty[i][1]-Ty[i+1][1]), Ty[i+1][2]))
    Edge[Ty[i+1][2]].append((abs(Ty[i][1]-Ty[i+1][1]), Ty[i][2]))

Dist = [float("inf") for i in range(N)]
Vis = [False for i in range(N)]
Dist[0] = 0
Q = [(0, 0)]
heapq.heapify(Q)
Cost = 0
while Q:
    ncost, now = heapq.heappop(Q)
    if not Vis[now]:
        Vis[now] = True
        Cost += ncost
        for node in Edge[now]:
            if not Vis[node[1]]:
                if Dist[node[1]] > node[0]:
                    Dist[node[1]] = node[0]
                    heapq.heappush(Q, (node[0], node[1]))

print(Cost)