import sys
import heapq
input = sys.stdin.readline

class Node:
    def __init__(self, id):
        self.id = id
        self.check = False
        self.link = []
        self.cost = []
    
    def __lt__(self, other):
        return self.id < other.id

def main():
    N = int(input())
    
    nodes = [Node(i) for i in range(N)]

    xy = []
    for i in range(N):
        x, y = map(int, input().split())
        xy.append((i, x, y))
    
    for t in range(2):
        if t == 0:
            xy = sorted(xy, key=lambda x: x[1])# x昇順
        else:
            xy = sorted(xy, key=lambda x: x[2])# y昇順
        p_n, p_x, p_y = xy[0]
        for i in range(1, N):
            n, x, y = xy[i]
            if t == 0:
                cost = abs(x - p_x)# x
            else:
                cost = abs(y - p_y)# y
            nodes[p_n].link.append(nodes[n])
            nodes[p_n].cost.append(cost)
            nodes[n].link.append(nodes[p_n])
            nodes[n].cost.append(cost)
            p_n, p_x, p_y = n, x, y
    q = []
    ans = 0
    heapq.heappush(q, (0, nodes[0]))# edge_cost, node
    while len(q) > 0:
        edge_cost, node = heapq.heappop(q)
        if node.check:
            continue
        node.check = True
        ans += edge_cost
        for i, next_node in enumerate(node.link):
            if not next_node.check:
                heapq.heappush(q, (node.cost[i], next_node))
    print(ans)

if __name__ == "__main__":
    main()