#!/usr/bin/env python
# coding: utf-8

def ri():
    return int(input())

def rl():
    return list(input().split())

def rli():
    return list(map(int, input().split()))

def main():
    n = ri()
    lp = []
    for i in range(n):
        x, y = rli()
        lp.append((i, x, y))
    lp.sort(key=lambda e: e[1])
    connects = []
    for i in range(n-1):
        cost = lp[i+1][1]-lp[i][1]
        connects.append((cost, lp[i][0], lp[i+1][0]))
    lp.sort(key=lambda e: e[2])
    for i in range(n-1):
        cost = lp[i+1][2]-lp[i][2]
        connects.append((cost, lp[i][0], lp[i+1][0]))
    connects.sort()
    used = set()
    ans = 0
    for c in connects:
        if c[1] in used and c[2] in used:
            continue
        used.add(c[1])
        used.add(c[2])
        ans += c[0]
        if len(used) == n:
            break
    print(ans)



if __name__ == '__main__':
    main()
