import heapq
n = int(input())
xy = []
yx = []
for i in range(n):
    xi, yi = map(int, input().split())
    xy.append((xi, yi, i))
    yx.append((yi, xi, i))
xy = list(sorted(xy))
yx = list(sorted(yx))
gr = {u: [] for u in range(n)}
for i in range(n - 1):
    u = xy[i][2]
    v = xy[i + 1][2]
    c = min(abs(xy[i + 1][0] - xy[i][0]), abs(xy[i + 1][1] - xy[i][1]))
    gr[u].append((c, v))
    gr[v].append((c, u))
    u = yx[i][2]
    v = yx[i + 1][2]
    c = min(abs(yx[i + 1][0] - yx[i][0]), abs(yx[i + 1][1] - yx[i][1]))
    gr[u].append((c, v))
    gr[v].append((c, u))
added = [False for _ in range(n + 1)]
cnt = 1
ans = 0
hq = []
heapq.heappush(hq, (0, 1))
while 0 < len(hq):
    c, u = heapq.heappop(hq)
    if not added[u]:
        added[u] = True
        ans += c
        for p in gr[u]:
            heapq.heappush(hq, p)

print(ans)