import java.util.*

fun main(args: Array<String>) {
    val n = readLine()!!.toInt()
    val nodes: Array<Node> = Array(n) { i ->
        readLine()!!.split(" ").map { it.toInt() }.let { Node(i, it[0], it[1]) }
    }
    val edges: ArrayList<Edge> = ArrayList(2 * n)
    nodes.sortBy { it.x }
    for (i in 0 until n - 1) {
        val a = nodes[i]
        val b = nodes[i + 1]
        val d = b.x - a.x
        edges.add(Edge(a.id, b.id, d))
    }
    nodes.sortBy { it.y }
    for (i in 0 until n - 1) {
        val a = nodes[i]
        val b = nodes[i + 1]
        val d = b.y - a.y
        edges.add(Edge(a.id, b.id, d))
    }
    edges.sortBy { it.dist }
    var d = 0L
    val uf = UnionFind(n)
    edges.forEach {
        if (!uf.hasSameRoot(it.from, it.to)) {
            d += it.dist
            uf.unite(it.from, it.to)
        }
    }
    println(d)
}

class Node(val id: Int, val x: Int, val y: Int)

class Edge(val from: Int, val to: Int, val dist: Int)

class UnionFind(size: Int) {
    private var data: Array<Int> = Array(size) { -1 }

    fun unite(x: Int, y: Int) {
        val x = find(x)
        val y = find(y)
        if (data[x] > data[y]) {
            val temp = data[x]
            data[x] = data[y]
            data[y] = temp
        }
        data[x] += data[y]
        data[y] = x
    }

    fun find(k: Int): Int {
        if (this.data[k] < 0) return k
        data[k] = find(data[k])
        return data[k]
    }

    fun hasSameRoot(x: Int, y: Int) = find(x) == find(y)

    fun size(k: Int) = -data[find(k)]
}