def main():
    n = int(input())
    city = []
    for i in range(n):
        x,y = map(int, input().split())
        city.append((x,y,i))
    edges = []
    # x
    city.sort()
    for i in range(n-1):
        dist = city[i+1][0] - city[i][0]
        edges.append((dist, city[i][2], city[i+1][2]))
    # y
    city.sort(key=lambda x:x[1])
    for i in range(n-1):
        dist = city[i+1][1] - city[i][1]
        edges.append((dist, city[i][2], city[i+1][2]))

    s = set()
    edges.sort()
    ans = 0
    cnt = 0
    while len(s) < n:
        dist, from_, to = edges[cnt]
        if from_ not in s or to not in s:
            s.add(from_)
            s.add(to)
            ans += dist
        cnt += 1
    print(ans)

if __name__ == '__main__':
    main()