

fun main(arg: Array<String>) {

    val n = readLine()!!.toInt()

    val p = Array(n) { i ->
        readLine()!!.split(" ").map { it.toInt() }.let { intArrayOf(i, it[0], it[1]) }
    }

    val edge = ArrayList<IntArray>()

    p.sortBy { it[1] }
    for (i in 0..n - 2) {
        val d = Math.abs(p[i][1] - p[i + 1][1])
        edge.add(intArrayOf(p[i][0], p[i + 1][0], d))
    }

    p.sortBy { it[2] }
    for (i in 0..n - 2) {
        val d = Math.abs(p[i][2] - p[i + 1][2])
        edge.add(intArrayOf(p[i][0], p[i + 1][0], d))
    }

    edge.sortBy { it[2] }

    val uf = UnionFind(n)
    var ret = 0L

    edge.forEach {
        if (!uf.same(it[0], it[1])) {
            uf.union(it[0], it[1])
            ret += it[2]
        }
    }
    println(ret)
}

class UnionFind(size: Int) {
    val par = IntArray(size) { -1 }

    fun same(x: Int, y: Int) = root(x) == root(y)

    fun union(x: Int, y: Int) {
        val rx = root(x)
        val ry = root(y)
        if (rx == ry) return
        par[rx] += par[ry]
        par[ry] = x
    }

    fun root(x: Int): Int {
        if (par[x] < 0) return x
        par[x] = root(par[x])
        return par[x]
    }
}
