#[allow(unused_imports)]
use itertools::Itertools;
#[allow(unused_imports)]
use itertools_num::ItertoolsNum;
#[allow(unused_imports)]
use std::cmp;
#[allow(unused_imports)]
use std::iter;
#[allow(unused_imports)]
use superslice::*;

pub struct UnionFind {
    parents: Vec<usize>,
    sizes: Vec<usize>,
    total: usize,
}

impl UnionFind {
    pub fn new(n: usize) -> UnionFind {
        UnionFind {
            parents: (0..n).collect::<Vec<usize>>(),
            sizes: vec![1; n],
            total: n,
        }
    }

    pub fn find(&mut self, x: usize) -> usize {
        if x == self.parents[x] {
            x
        } else {
            self.parents[x] = self.find(self.parents[x]);
            self.parents[x]
        }
    }

    pub fn is_same(&mut self, x: usize, y: usize) -> bool {
        self.find(x) == self.find(y)
    }

    pub fn unite(&mut self, x: usize, y: usize) -> bool {
        let parent_x = self.find(x);
        let parent_y = self.find(y);
        if parent_x == parent_y {
            return false;
        }

        let (large, small) = if self.sizes[parent_x] < self.sizes[parent_y] {
            (parent_y, parent_x)
        } else {
            (parent_x, parent_y)
        };

        self.parents[small] = large;
        self.sizes[large] += self.sizes[small];
        self.sizes[small] = 0;
        self.total -= 1;
        true
    }
}

pub struct MinimumSpanningTree<T> {
    n: usize,
    edges: Vec<(usize, usize, T)>, // (i, j, cost)
    selected: Vec<(usize, usize, T)>,
    total_cost: T,
}

impl<T> MinimumSpanningTree<T>
where
    T: Copy
        + num::Zero
        + std::ops::Add<Output = T>
        + std::ops::Sub<Output = T>
        + std::ops::AddAssign
        + std::cmp::Ord,
{
    /// Create new instance
    pub fn new(n: usize, edges: &Vec<(usize, usize, T)>) -> Self {
        MinimumSpanningTree {
            n,
            edges: edges.clone(),
            selected: vec![],
            total_cost: num::Zero::zero(),
        }
    }

    /// Kruskal's algorithm
    /// O(E log E}
    pub fn kruskal(&mut self) {
        let mut uf = UnionFind::new(self.n);
        self.selected = vec![];
        self.total_cost = num::Zero::zero();

        self.edges.sort_by_cached_key(|x| x.2);
        for &(x, y, cost) in self.edges.iter() {
            if !uf.is_same(x, y) {
                uf.unite(x, y);
                self.selected.push((x, y, cost));
                self.total_cost += cost;
            }
        }
    }
}

fn run() {
    let (r, w) = (std::io::stdin(), std::io::stdout());
    let mut sc = IO::new(r.lock(), w.lock());

    let n: usize = sc.read();
    let mut xyi = sc
        .read_pairs::<i64>(n)
        .into_iter()
        .enumerate()
        .map(|(i, (x, y))| (x, y, i))
        .collect_vec();

    let mut edges = vec![];
    xyi.sort();
    for i in 0..(n - 1) {
        let dist = cmp::min(
            (xyi[i].0 - xyi[i + 1].0).abs(),
            (xyi[i].1 - xyi[i + 1].1).abs(),
        );
        edges.push((xyi[i].2, xyi[i + 1].2, dist));
    }
    xyi.sort_by_cached_key(|&(x, y, i)| y);
    for i in 0..(n - 1) {
        let dist = cmp::min(
            (xyi[i].0 - xyi[i + 1].0).abs(),
            (xyi[i].1 - xyi[i + 1].1).abs(),
        );
        edges.push((xyi[i].2, xyi[i + 1].2, dist));
    }

    let mut mst = MinimumSpanningTree::new(n, &edges);
    mst.kruskal();
    println!("{}", mst.total_cost);
}

fn main() {
    std::thread::Builder::new()
        .name("run".into())
        .stack_size(256 * 1024 * 1024)
        .spawn(run)
        .unwrap()
        .join()
        .unwrap();
}

pub struct IO<R, W: std::io::Write>(R, std::io::BufWriter<W>);

impl<R: std::io::Read, W: std::io::Write> IO<R, W> {
    pub fn new(r: R, w: W) -> IO<R, W> {
        IO(r, std::io::BufWriter::new(w))
    }
    pub fn write<S: std::ops::Deref<Target = str>>(&mut self, s: S) {
        use std::io::Write;
        self.1.write(s.as_bytes()).unwrap();
    }
    pub fn read<T: std::str::FromStr>(&mut self) -> T {
        use std::io::Read;
        let buf = self
            .0
            .by_ref()
            .bytes()
            .map(|b| b.unwrap())
            .skip_while(|&b| b == b' ' || b == b'\n' || b == b'\r' || b == b'\t')
            .take_while(|&b| b != b' ' && b != b'\n' && b != b'\r' && b != b'\t')
            .collect::<Vec<_>>();
        unsafe { std::str::from_utf8_unchecked(&buf) }
            .parse()
            .ok()
            .expect("Parse error.")
    }
    pub fn read_vec<T: std::str::FromStr>(&mut self, n: usize) -> Vec<T> {
        (0..n).map(|_| self.read()).collect()
    }
    pub fn read_pairs<T: std::str::FromStr>(&mut self, n: usize) -> Vec<(T, T)> {
        (0..n).map(|_| (self.read(), self.read())).collect()
    }
    pub fn read_pairs_1_indexed(&mut self, n: usize) -> Vec<(usize, usize)> {
        (0..n)
            .map(|_| (self.read::<usize>() - 1, self.read::<usize>() - 1))
            .collect()
    }
    pub fn read_chars(&mut self) -> Vec<char> {
        self.read::<String>().chars().collect()
    }
    pub fn read_char_grid(&mut self, n: usize) -> Vec<Vec<char>> {
        (0..n).map(|_| self.read_chars()).collect()
    }
    pub fn read_matrix<T: std::str::FromStr>(&mut self, n: usize, m: usize) -> Vec<Vec<T>> {
        (0..n)
            .map(|_| (0..m).map(|_| self.read()).collect())
            .collect()
    }
}


Measured memory_bytes: 18292