# D
import numpy as np
N = int(input())
X = np.zeros(N, dtype=int)
Y = np.zeros(N, dtype=int)

for i in range(N):
    x, y = map(int, input().split())
    X[i] = x
    Y[i] = y

# edges
X_s = np.argsort(X)
Y_s = np.argsort(Y)

edge_list = []
edge_weight = []
for i in range(N-1):
    edge_list.append([X_s[i], X_s[i+1]])
    edge_weight.append(min(abs(X[X_s[i+1]] - X[X_s[i]]), abs(Y[X_s[i+1]] - Y[X_s[i]])))
    edge_list.append([Y_s[i], Y_s[i+1]])
    edge_weight.append(min(abs(X[Y_s[i+1]] - X[Y_s[i]]), abs(Y[Y_s[i+1]] - Y[Y_s[i]])))
    
# sort edges
sel = np.argsort(np.array(edge_weight))

# union find tree
uf = dict()
for i in range(N):
    uf[i] = [i, 0]

res = 0
flg = np.zeros(N)

for s in sel:
    m, n = edge_list[s]
    # find union
    gr_m = m
    gr_n = n
    dep_m = 0
    dep_n = 0
    while gr_m != uf[gr_m][0]:
        gr_m = uf[gr_m][0]
        dep_m += 1
    uf[gr_m][1] = max(uf[gr_m][1], dep_m)
    uf[m] = [gr_m, dep_m]
    while gr_n != uf[gr_n][0]:
        gr_n = uf[gr_n][0]
        dep_n += 1
    uf[gr_n][1] = max(uf[gr_n][1], dep_n)
    uf[n] = [gr_n, dep_n]
    if gr_m == gr_n:
        pass
    else:
        res += edge_weight[s]
        if dep_m > dep_n:
            uf[gr_n] = [gr_m, dep_m]
        elif dep_m > dep_n:
            uf[gr_n] = [gr_m, dep_m+1]
        else:
            uf[gr_m] = [gr_n, dep_n]
print(res)