fun main(args: Array<String>) {
        val n = nextInt()
        val xy = Array(n) { listOfLong(-1) }

        val sx = (0 until n).sortedBy { xy[it][0] }
        val sy = (0 until n).sortedBy { xy[it][1] }

        val edges = mutableListOf<Triple<Int, Int, Long>>()
        for (n in 1 until n) {
            val fx = sx[n]
            val tx = sx[n - 1]
            val dx = xy[fx][0] - xy[tx][0]
            edges.add(Triple(fx, tx, dx))

            val fy = sy[n]
            val ty = sy[n - 1]
            val dy = xy[fy][1] - xy[ty][1]
            edges.add(Triple(fy, ty, dy))
        }
        edges.sortBy { it.third }

        val uf = UnionFind(n)
        var ans = 0L
        for (n in edges.indices) {
            if (uf.unite(edges[n].first, edges[n].second)) {
                ans += edges[n].third
            }
        }

        println(ans)
    }





fun next() = readLine()!!
fun nextInt() = next().toInt()
fun nextLong() = next().toLong()
fun listOfString() = next().split(" ")
fun listOfInt() = listOfString().map(String::toInt)
fun listOfInt(vararg deltas: Int) = listOfString().map { Integer.parseInt(it) }.mapIndexed { index, int -> int + deltas[index % deltas.size] }
fun listOfLong(offset: Long = 0L) = listOfString().map { it.toLong() + offset}

class UnionFind(n: Int) {
    var rank: IntArray
    var par:  IntArray
    var size: IntArray
    init {
        this.rank = IntArray(n) { 0 }
        this.par  = IntArray(n) { it }
        this.size = IntArray(n) { 1 }
    }
    fun union(x: Int, y: Int): Boolean {
        var rx = this.root(x)
        var ry = this.root(y)
        if (rx == ry) return false
        if (this.rank[rx] < this.rank[ry]) {
            val w = rx
            rx = ry
            ry = w
        } else if (this.rank[rx] == this.rank[ry]) {
            this.rank[rx] += 1
        }
        this.par[ry] = rx
        this.size[rx] += this.size[ry]
        return true
    }
    fun find(x: Int): Int {
        if (this.par[x] == x) return x
        else {
            this.par[x] = this.find(this.par[x])
            return this.par[x]
        }
    }
    fun isSame(x: Int, y: Int) = this.root(x) == this.root(y)
    fun size(x: Int): Int = this.size[this.find(x)]
    fun root(x: Int): Int = this.find(x)
    fun unite(x: Int, y: Int) = this.union(x, y)
}
