CodeEff/ECCO huggingface dataset:
# Original solution
import heapq

n=int(eval(input()))
G=[]
for index in range(n):
    x,y=list(map(int,input().split()))
    G.append((index,x,y))

#print(G)

D=[[] for _ in range(n)]

xG=sorted(G,key=lambda x:x[1])
for index_x in range(n-1):
    nowx=xG[index_x]
    nextx=xG[index_x+1]
    distx=nextx[1]-nowx[1]
    D[nowx[0]].append([distx,nextx[0]])
    D[nextx[0]].append([distx,nowx[0]])

#print(xG)

yG=sorted(G,key=lambda x:x[2])
for index_y in range(n-1):
    nowy=yG[index_y]
    nexty=yG[index_y+1]
    disty=nexty[2]-nowy[2]
    D[nowy[0]].append([disty,nexty[0]])
    D[nexty[0]].append([disty,nowy[0]])

#print(yG)

#print(D)

def prim_heap():
    used = [True] * n #True:不使用
    edgelist = []
    for e in D[0]:
        heapq.heappush(edgelist,e)
    used[0] = False
    res = 0
    while len(edgelist) != 0:
        minedge = heapq.heappop(edgelist)
        if not used[minedge[1]]:
            continue
        v = minedge[1]
        used[v] = False
        for e in D[v]:
            if used[e[1]]:
                heapq.heappush(edgelist,e)
        res += minedge[0]
    return res

ans=prim_heap()
print(ans)






# Optimized solution
class UnionFind():
    def __init__(self, n):
        self.n = n
        self.parents = [-1] * n

    def find(self, x):
        if self.parents[x] < 0:
            return x
        else:
            self.parents[x] = self.find(self.parents[x])
            return self.parents[x]

    def union(self, x, y):
        x = self.find(x)
        y = self.find(y)

        if x == y:
            return

        if self.parents[x] > self.parents[y]:
            x, y = y, x

        self.parents[x] += self.parents[y]
        self.parents[y] = x

    def size(self, x):
        return -self.parents[self.find(x)]

    def same(self, x, y):
        return self.find(x) == self.find(y)

    def members(self, x):
        root = self.find(x)
        return [i for i in range(self.n) if self.find(i) == root]

    def roots(self):
        return [i for i, x in enumerate(self.parents) if x < 0]

    def group_count(self):
        return len(self.roots())

    def all_group_members(self):
        return {r: self.members(r) for r in self.roots()}

    def __str__(self):
        return '\n'.join('{}: {}'.format(r, self.members(r)) for r in self.roots())

N=int(eval(input()))
G=[]
for i in range(N):
    x,y=list(map(int,input().split()))
    G.append((x,y,i))

Gx=sorted(G,key=lambda x:x[0])
Gy=sorted(G,key=lambda x:x[1])

newG=[]
for i in range(N-1):
    now=Gx[i]
    next=Gx[i+1]
    dist=abs(now[0]-next[0])
    newG.append((dist,now[2],next[2]))

for i in range(N-1):
    now=Gy[i]
    next=Gy[i+1]
    dist=abs(now[1]-next[1])
    newG.append((dist,now[2],next[2]))

newG.sort()

uf=UnionFind(N)
count=N
ans=0
for c,i,j in newG:
    if count==0:
        break

    if not uf.same(i,j):
        ans+=c
        uf.union(i,j)
        count-=1

print(ans)
# Original solution
def main():
    import heapq
    class unionfind():
        #size:要素数,tree：unionfind木
        def __init__(self,size):#self,要素数
            self.size=size
            self.tree=[[i,1] for i in range(self.size)]#root,depth
        
        #rootを探す
        def root(self,index):
            if self.tree[index][0]==index:
                return index
            else:
                self.tree[index][0]=self.root(self.tree[index][0])
                return self.tree[index][0]
    
        #結合
        def unite(self,index1,index2):
            r1=self.root(index1)
            r2=self.root(index2)
            if r1!=r2:
                d1,d2=self.tree[r1][1],self.tree[r2][1]
                if d1<=d2:
                    self.tree[r1][0]=r2
                    self.tree[r2][1]=max(d1+1,d2)
                else:
                    self.tree[r2][0]=r1
                    self.tree[r1][1]=max(d2+1,d1)
    
        #同じか判定
        def same(self,index1,index2):
            r1=self.root(index1)
            r2=self.root(index2)
            return r1==r2
    
    n=int(eval(input()))
    xy=[list(map(int,input().split())) for _ in [0]*n]
    xyz=[xy[i]+[i] for i in range(n)]
    x_sort=sorted(xyz,key=lambda x:x[0])
    y_sort=sorted(xyz,key=lambda x:x[1])
    g=[]
    heapq.heapify(g)
    for i in range(n-1):
        heapq.heappush(g,[abs(x_sort[i+1][0]-x_sort[i][0]),x_sort[i][2],x_sort[i+1][2]])
    for i in range(n-1):
        heapq.heappush(g,[abs(y_sort[i+1][1]-y_sort[i][1]),y_sort[i][2],y_sort[i+1][2]])
    u=unionfind(n)
    cnt=0
    while g:
        d,i,j=heapq.heappop(g)
        if u.same(i,j)==False:
            cnt+=d
            u.unite(i,j)
    print(cnt)
main()

# Optimized solution
def main():
    import heapq
    def root(index):
        if tree[index][0]==index:
            return index
        else:
            tree[index][0]=root(tree[index][0])
            return tree[index][0]

    def unite(index1,index2):
        r1=root(index1)
        r2=root(index2)
        if r1!=r2:
            d1,d2=tree[r1][1],tree[r2][1]
            if d1<=d2:
                tree[r1][0]=r2
                tree[r2][1]=max(d1+1,d2)
            else:
                tree[r2][0]=r1
                tree[r1][1]=max(d2+1,d1)

    def same(index1,index2):
        return root(index1)==root(index2)
    
    n=int(eval(input()))
    xy=[list(map(int,input().split())) for _ in [0]*n]
    xyz=[xy[i]+[i] for i in range(n)]
    x_sort=sorted(xyz,key=lambda x:x[0])
    y_sort=sorted(xyz,key=lambda x:x[1])
    
    tree=[[i,1] for i in range(n)]#root,depth
    g=[]
    heapq.heapify(g)
    for i in range(n-1):
        heapq.heappush(g,[abs(x_sort[i+1][0]-x_sort[i][0]),x_sort[i][2],x_sort[i+1][2]])
    for i in range(n-1):
        heapq.heappush(g,[abs(y_sort[i+1][1]-y_sort[i][1]),y_sort[i][2],y_sort[i+1][2]])

    cnt=0
    while g:
        d,i,j=heapq.heappop(g)
        if same(i,j)==False:
            cnt+=d
            unite(i,j)
    print(cnt)
main()
# Original solution
import sys
from collections import Counter, deque, defaultdict
from math import factorial
import heapq, bisect
import math
import itertools
sys.setrecursionlimit(10 ** 5 + 10)
INF = 10**15 +5
def input(): return sys.stdin.readline().strip()
def INT(): return int(eval(input()))
def MAP(): return list(map(int, input().split()))
def LIST(): return list(map(int, input().split()))

n = INT()
position = [[]for i in range(n)]
for i in range(n):
    a, b= MAP()
    position[i] = (a, b)

def prim():
    res = 0
    used = [False]*n
    que = []
    heapq.heapify(que)
    used[0] = True
    for i in range(1, n):
        distance = min(abs(position[0][0]-position[i][0]), abs(position[0][1]-position[i][1]))
        heapq.heappush(que,(distance,i))
    while(len(que) > 0):
        cost, vertex = heapq.heappop(que)
        if used[vertex]:continue
        res += cost
        used[vertex] = True
        for i in range(n):
            if used[i]:continue
            distance = min(abs(position[vertex][0]-position[i][0]), abs(position[vertex][1]-position[i][1]))
            heapq.heappush(que,(distance, i))
    return res

print((prim()))

# Optimized solution
import sys
from collections import Counter, deque, defaultdict
from math import factorial
import heapq, bisect
import math
import itertools
sys.setrecursionlimit(10 ** 5 + 10)
INF = 10**15 +5
def input(): return sys.stdin.readline().strip()
def INT(): return int(eval(input()))
def MAP(): return list(map(int, input().split()))
def LIST(): return list(map(int, input().split()))

n = INT()
G = [[]for i in range(n)]   
position = [[]for i in range(n)]
for i in range(n):
    a, b= MAP()
    position[i] = (i, a, b)
position_x = sorted(position, key = lambda x:x[1])
position_y = sorted(position, key = lambda x:x[2])

for i in range(1,n):
    G[position_x[i][0]].append((position_x[i][1]-position_x[i-1][1], position_x[i-1][0]))
    G[position_x[i-1][0]].append((position_x[i][1]-position_x[i-1][1], position_x[i][0]))
    G[position_y[i][0]].append((position_y[i][2]-position_y[i-1][2], position_y[i-1][0]))
    G[position_y[i-1][0]].append((position_y[i][2]-position_y[i-1][2], position_y[i][0]))

def prim(G):
    res = 0
    used = [False]*n
    que = []
    heapq.heapify(que)
    used[0] = True
    for Gs in G[0]:
        heapq.heappush(que,Gs)
    while(len(que) > 0):
        cost, vertex = heapq.heappop(que)
        if used[vertex]:continue
        res += cost
        used[vertex] = True
        for Gs in G[vertex]:
            if used[Gs[1]]:continue
            heapq.heappush(que,Gs)
    return res

print((prim(G)))
# Original solution
from collections import deque
import sys

sys.setrecursionlimit(2000000000)
 
n = int(eval(input()))
nodes = []
done = [0 for _ in range(n)]
par = {}
for _ in range(n):
    x, y = list(map(int,input().split()))
    nodes.append((x,y))
    par[(x,y)]=(x,y)
nodesx = sorted(nodes)
nodesy = sorted(nodes,key=lambda z:z[1])
s = []
 
for i in range(n-1):
    xcost =nodesx[i+1][0]-nodesx[i][0]
    ycost =nodesy[i+1][1]-nodesy[i][1]
    s.append((xcost,(nodesx[i+1],nodesx[i])))
    s.append((ycost,(nodesy[i+1],nodesy[i])))
s.sort()
def root(node,par):
    if node == par[node]:
        return node
    else:
        par[node] =root(par[node],par)
        return par[node]
def unite(node1,node2,par):
    par[root(node1,par)] = root(node2,par)
ans = 0
count =0
for cost,(node1,node2) in s:
    if count == n-1:
        break
    root1 =root(node1,par)
    root2 =root(node2,par)
    if root1 != root2:
        unite(node1,node2,par)
        ans +=cost
        count += 1
print(ans)


# Optimized solution
from collections import deque
import sys
 
sys.setrecursionlimit(2000000000)
 
n = int(eval(input()))
nodes = []
done = [0 for _ in range(n)]
par = {}
for _ in range(n):
    x, y = list(map(int,input().split()))
    nodes.append((x,y))
    par[(x,y)]=(x,y)
nodesx = sorted(nodes)
nodesy = sorted(nodes,key=lambda z:z[1])
s = []
m = len(set(nodes))
for i in range(n-1):
    xcost =nodesx[i+1][0]-nodesx[i][0]
    ycost =nodesy[i+1][1]-nodesy[i][1]
    s.append((xcost,(nodesx[i+1],nodesx[i])))
    s.append((ycost,(nodesy[i+1],nodesy[i])))
s.sort()
s = deque(s)
def root(node,par):
    if node == par[node]:
        return node
    else:
        par[node] =root(par[node],par)
        return par[node]
def unite(node1,node2,par):
    par[root(node1,par)] = root(node2,par)
ans = 0
count =0
while count < m-1 :
    cost,(node1,node2) = s.popleft()
    root1 =root(node1,par)
    root2 =root(node2,par)
    if root1 != root2:
        unite(node1,node2,par)
        ans +=cost
        count += 1
print(ans)
# Original solution
# 解説

def solve() -> None:
    from collections import namedtuple
    from heapq import heappush, heappop
    from operator import attrgetter
    pt = namedtuple('pt', 'x y idx')

    n = int(eval(input()))
    cities = []
    for idx in range(n):
        x, y = list(map(int, input().split()))
        cities.append(pt(x=x, y=y, idx=idx))

    g = tuple(set() for _ in range(n))

    xs = sorted(cities, key=attrgetter('x'))
    for a, b in zip(xs, xs[1:]):
        g[a.idx].add((b.x - a.x, b.idx))
        g[b.idx].add((b.x - a.x, a.idx))

    ys = sorted(cities, key=attrgetter('y'))
    for a, b in zip(ys, ys[1:]):
        g[a.idx].add((b.y - a.y, b.idx))
        g[b.idx].add((b.y - a.y, a.idx))

    ret = 0
    h = [(0, 0)]
    used = [False] * n
    count = 0

    while True:
        c, v = heappop(h)
        if used[v]:
            continue
        used[v] = True
        count += 1
        ret += c
        if count == n:
            break
        for c_, u in g[v]:
            if used[u]:
                continue
            heappush(h, (c_, u))

    return ret


if __name__ == '__main__':
    print((solve()))

# 最小全域木


# Optimized solution
def solve_abc065d():
    from collections import namedtuple
    from operator import attrgetter
    from itertools import tee
    import sys

    input = sys.stdin.readline

    City = namedtuple('City', 'x y idx')
    Edge = namedtuple('Edge', 'cost a b')
    N = int(eval(input()))

    cities = []
    for city_idx in range(N):
        x, y = list(map(int, input().split()))
        c_ = City(x, y, city_idx)
        cities.append(c_)
    cities_x_asc = sorted(cities, key=attrgetter('x'))
    cities_y_asc = sorted(cities, key=attrgetter('y'))

    edges = []

    it_x = iter(cities_x_asc)
    gx1, gx2 = tee(it_x, 2)
    next(gx2)
    for c1, c2 in zip(gx1, gx2):
        d_ = c2.x - c1.x
        e_ = Edge(d_, c1.idx, c2.idx)
        edges.append(e_)
    # x方向にN-1本の辺を張る

    it_y = iter(cities_y_asc)
    gy1, gy2 = tee(it_y, 2)
    next(gy2)
    for c1, c2 in zip(gy1, gy2):
        d_ = c2.y - c1.y
        e_ = Edge(d_, c1.idx, c2.idx)
        edges.append(e_)
    # y方向にN-1本の辺を張る

    edges.sort(key=attrgetter('cost'))

    # <Kruskal’s Algorithm>
    # https://tjkendev.github.io/procon-library/python/graph/min_st_kruskal.html
    # E = [(cost, v, w), ...]
    #   G上の全ての辺(v, w)とそのcostを含むlist

    # Union-Findを使うことで頂点間の連結判定を行う
    *p, = list(range(N))

    def root(x):
        if x == p[x]:
            return x
        p[x] = y = root(p[x])
        return y

    def unite(x, y):
        px = root(x)
        py = root(y)
        if px == py:
            return 0
        if px < py:
            p[py] = px
        else:
            p[px] = py
        return 1

    mi = 0
    for e_ in edges:
        if unite(e_.a, e_.b):
            mi += e_.cost

    # miが最小全域木の解

    print(mi)
    return


if __name__ == '__main__':
    solve_abc065d()
# Original solution
import sys
sys.setrecursionlimit(10**6)
from heapq import heappop, heappush

icase=0
if icase==0:
    n=int(eval(input()))
    xy=[[0]*2 for i in range(n)]
    for i in range(n):
        xy[i]=list(map(int,input().split()))
elif icase==1:    
    n=3
    xy=[[1, 5], [3, 9], [7, 8]]
elif icase==2:    
    n=6
    xy=[[8, 3], [4, 9], [12, 19], [18, 1], [13, 5], [7, 6]]

#xy = list(map(list, set(map(tuple, xy))))
xy.sort()
xy=xy[:n]

pair_lst = [i for i in range(n)]
que=[]
for i in range(n-1):
    for j in range(i+1,n):
        wi=min(abs(xy[i][0]-xy[j][0]),abs(xy[i][1]-xy[j][1]))
        heappush(que,(wi,i,j))

def find(x):
    if x == pair_lst[x]:
        return x
    else:
        tmp = find(pair_lst[x])
        pair_lst[x] = tmp
        return tmp

length_sum = 0
while que:
    w, s, t = heappop(que)
    root_s = find(s)
    root_t = find(t)
    if root_s != root_t:
        pair_lst[root_s] = root_t
        length_sum += w

print(length_sum)    


# Optimized solution
import sys
sys.setrecursionlimit(10**6)
from heapq import heappop, heappush,heapify

icase=0
if icase==0:
    n=int(eval(input()))
    xy=[[0]*2 for i in range(n)]
    x=[0]*n
    y=[0]*n
    for i in range(n):
#        xy[i]=list(map(int,input().split()))
        x[i],y[i]=list(map(int,input().split()))
elif icase==1:    
    n=3
#    xy=[[1, 5], [3, 9], [7, 8]]
    x=[1, 3, 7]
    y=[5, 9, 8]
elif icase==2:    
    n=6
#    xy=[[8, 3], [4, 9], [12, 19], [18, 1], [13, 5], [7, 6]]
    x=[8, 4, 12,18,13,7]
    y=[3, 9, 19, 1, 5, 6]

xi=[[0]*2 for i in range(n)]
yi=[[0]*2 for i in range(n)]
for i in range(n):
    xi[i]=[x[i],i]
    yi[i]=[y[i],i]
    
xi.sort()
x=xi
y=yi.sort()
y=yi

pair_lst = [i for i in range(n)]
que=[]
for i in range(n-1):
    wi=x[i+1][0]-x[i][0]
    heappush(que,(wi,x[i][1],x[i+1][1]))
    wi=y[i+1][0]-y[i][0]
    heappush(que,(wi,y[i][1],y[i+1][1]))

def find(x):
    if x == pair_lst[x]:
        return x
    else:
        tmp = find(pair_lst[x])
        pair_lst[x] = tmp
        return tmp

icnt=0
length_sum = 0
while que:
    w, s, t = heappop(que)
#    print(w,s,t)
    root_s = find(s)
    root_t = find(t)
    if root_s != root_t:
        pair_lst[root_s] = root_t
        length_sum += w
        icnt+=1
#        print(icnt)

print(length_sum)
# Original solution
import sys
import heapq
from collections import defaultdict
sys.setrecursionlimit(10 ** 7)

# 最小全域木
# プリム法 #
# 部分木から、最小コストの辺を貪欲に追加

# Kruskal法 #
# クラスカル法 #
# 辺でソートして、最小コストの辺から、ループにならないよう貪欲に追加
# UnionFindを使う


N = int(eval(input()))

# x,yでそれぞれソート
POINT_x = []
POINT_y = []
for _ in range(N):
    x, y = list(map(int, input().split()))
    POINT_x.append((x, y))
    POINT_y.append((x, y))

POINT_x = sorted(POINT_x, key=lambda x: x[0])
POINT_y = sorted(POINT_y, key=lambda x: x[1])

EDGE = defaultdict(list)
for i in range(N):
    p = POINT_x[i]

    if i != 0:
        prev = POINT_x[i-1]
        EDGE[p].append((abs(p[0]-prev[0]), prev))

    if i != N-1:
        nxt = POINT_x[i+1]
        EDGE[p].append((abs(p[0]-nxt[0]), nxt))

for i in range(N):
    p = POINT_y[i]

    if i != 0:
        prev = POINT_y[i-1]
        EDGE[p].append((abs(p[1]-prev[1]), prev))

    if i != N-1:
        nxt = POINT_y[i+1]
        EDGE[p].append((abs(p[1]-nxt[1]), nxt))


INF = 10 ** 12
mincost = [INF] * N
used = defaultdict(lambda: False)

point = POINT_x[0]
used[point] = True
q = []
ans = 0

for e in EDGE[point]:
    heapq.heappush(q, e)

while(True):
    update = False
    for _ in range(len(q)):
        cost, point = heapq.heappop(q)
        if used[point]:
            continue

        update = True
        ans += cost
        used[point] = True

        for e in EDGE[point]:
            heapq.heappush(q, e)

    if not update:
        break

print(ans)


# Optimized solution
import sys
import heapq
from collections import defaultdict
sys.setrecursionlimit(10 ** 7)

# 最小全域木
# プリム法 #
# 部分木から、最小コストの辺を貪欲に追加

# Kruskal法 #
# クラスカル法 #
# 辺でソートして、最小コストの辺から、ループにならないよう貪欲に追加
# UnionFindを使う


N = int(eval(input()))

# x,yでそれぞれソート
POINT_x = []
POINT_y = []
for _ in range(N):
    x, y = list(map(int, input().split()))
    POINT_x.append((x, y))
    POINT_y.append((x, y))

POINT_x = sorted(POINT_x, key=lambda x: x[0])
POINT_y = sorted(POINT_y, key=lambda x: x[1])

EDGE = defaultdict(list)
for i in range(N):
    p = POINT_x[i]

    if i != 0:
        prev = POINT_x[i-1]
        EDGE[p].append((abs(p[0]-prev[0]), prev))

    if i != N-1:
        nxt = POINT_x[i+1]
        EDGE[p].append((abs(p[0]-nxt[0]), nxt))

for i in range(N):
    p = POINT_y[i]

    if i != 0:
        prev = POINT_y[i-1]
        EDGE[p].append((abs(p[1]-prev[1]), prev))

    if i != N-1:
        nxt = POINT_y[i+1]
        EDGE[p].append((abs(p[1]-nxt[1]), nxt))


INF = 10 ** 12
mincost = [INF] * N
used = defaultdict(lambda: False)

point = POINT_x[0]
used[point] = True
q = []
ans = 0

for e in EDGE[point]:
    heapq.heappush(q, e)

while(True):
    update = False
    for _ in range(len(q)):
        cost, point = heapq.heappop(q)
        if used[point]:
            continue

        update = True
        ans += cost
        used[point] = True

        for e in EDGE[point]:
            if not used[e[1]]:
                heapq.heappush(q, e)

    if not update:
        break

print(ans)
# Original solution
from heapq import *

# Aの中でxの根を求める
def find(A,x):
    p = A[x]
    if p == x:
        return x
    a = find(A,p)
    A[x] = a
    return a

# Aのリストでxとyの属する集合の併合
def union(A, x, y):
    if find(A,x) > find(A,y):
        bx, by = find(A,y), find(A,x)
    else:
        bx, by = find(A,x), find(A,y)
    # 根をbxに統一
    A[by] = bx

N = int(eval(input()))
X = [(0,0)] * N
Y = [(0,0)] * N
E = [(0,0)] * N

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

X.sort()
Y.sort()
H = []
heapify(H)

for i in range(N - 1):
    x1, j1 = X[i]
    x2, j2 = X[i + 1]
    y1, k1 = Y[i]
    y2, k2 = Y[i + 1]
    # ヒープ構造を用いて常にHの最初に最小値を持ってくる
    # X座標とY座標でそれぞれHに追加
    heappush(H, (x2 - x1, j1, j2))
    heappush(H, (y2 - y1, k1, k2))

answer = 0
V = [i for i in range(N)]

while H:
    w, s, t = heappop(H)
    # sとtの集合が異なっていた時、道を作る
    if find(V, s) != find(V, t):
        union(V, s, t)
        answer += w

print(answer)


# Optimized solution
# D - Built?
from heapq import *

# Aでxの根を求める
def find(A, x):
    p = A[x]
    if p == x:
        return x
    a = find(A, p)
    A[x] = a
    return a

# Aでxとyの属する集合の併合
def union(A, x, y):
    if find(A, x) > find(A, y):
        bx, by = find(A, y), find(A, x)
    else:
        bx, by = find(A, x), find(A, y)
    # 根をbx(値の小さい方)に統一 
    A[by] = bx

N = int(eval(input()))
X = [(0,0)] * N
Y = [(0,0)] * N

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

X.sort()
Y.sort()
H = []
heapify(H)

for i in range(N - 1):
    x1, j1 = X[i]
    x2, j2 = X[i+1]
    y1, k1 = Y[i]
    y2, k2 = Y[i+1]
    # ヒープ構造を用いて常にHの先頭に最小値を持ってくる
    # X座標とY座標でそれぞれHに追加
    heappush(H, (x2 - x1, j1, j2))
    heappush(H, (y2 - y1, k1, k2))

answer = 0
V = [i for i in range(N)]

while H:
    w, s, t = heappop(H)
    # sとtの集合が異なっていた時、道を作る
    if find(V, s) != find(V, t):
        union(V, s, t)
        answer += w

print(answer)
# Original solution
from heapq import *

def find(x):
    parent = data[x]
    if parent < 0: return x
    root = find(parent)
    data[x] = root
    return root

def union(x, y):
    root, second = find(x), find(y)
    if root == second: return False
    if height[root] < data[second]:
        second, root = root, second
    data[root] += data[second]
    height[root] = max(height[root], height[second]+1)
    data[second] = root
    return True

N = int(eval(input()))
X = [(0,0)] * N
Y = [(0,0)] * N
E = [(0,0)] * N

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

X.sort()
Y.sort()
H = []

for i in range(N - 1):
    x1, j1 = X[i]
    x2, j2 = X[i + 1]
    y1, k1 = Y[i]
    y2, k2 = Y[i + 1]
    # ヒープ構造を用いて常にHの最初に最小値を持ってくる
    # X座標とY座標でそれぞれHに追加
    heappush(H, (x2 - x1, j1, j2))
    heappush(H, (y2 - y1, k1, k2))

answer = 0
data = [-1] * (N+1)  # 1-indexed rootには-sizeが入る
height = [0] * (N+1)

while H:
    w, s, t = heappop(H)
    # sとtの集合が異なっていた時、道を作る
    if union(s, t):
        answer += w

print(answer)


# Optimized solution
from heapq import *

def main():
    def find(x):
        parent = data[x]
        if parent < 0: return x
        root = find(parent)
        data[x] = root
        return root

    def union(x, y):
        root, second = find(x), find(y)
        if root == second: return False
        if height[root] < data[second]:
            second, root = root, second
        data[root] += data[second]
        height[root] = max(height[root], height[second]+1)
        data[second] = root
        return True

    N = int(eval(input()))
    X = [(0,0)] * N
    Y = [(0,0)] * N

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

    X.sort()
    Y.sort()
    H = []

    for i in range(N - 1):
        x1, j1 = X[i]
        x2, j2 = X[i + 1]
        y1, k1 = Y[i]
        y2, k2 = Y[i + 1]
        # ヒープ構造を用いて常にHの最初に最小値を持ってくる
        # X座標とY座標でそれぞれHに追加
        heappush(H, (x2 - x1, j1, j2))
        heappush(H, (y2 - y1, k1, k2))

    answer = 0
    data = [-1] * (N+1)  # 1-indexed rootには-sizeが入る
    height = [0] * (N+1)

    while H:
        w, s, t = heappop(H)
        # sとtの集合が異なっていた時、道を作る
        if union(s, t):
            answer += w

    print(answer)


if __name__ == "__main__":
    main()