#[allow(unused_imports)]
use std::cmp::{Ordering};

#[allow(unused_imports)]
use std::collections::{BTreeMap, BTreeSet, BinaryHeap, HashMap, HashSet, VecDeque};

#[allow(unused_imports)]
use std::io::{stdin, stdout, BufWriter, Write};

#[allow(unused_imports)]
use std::iter::FromIterator;

#[allow(unused_macros)]
macro_rules! min {
    ($x: expr) => ($x);
    ($x: expr, $($z: expr),+) => {{
        std::cmp::min($x, min!($($z),*))
    }}
}

#[allow(unused_macros)]
macro_rules! max {
    ($x: expr) => ($x);
    ($x: expr, $($z: expr),+) => {{
        std::cmp::max($x, max!($($z),*))
    }}
}

#[allow(unused_macros)]
macro_rules! get { 
    ([$t: ty]) => { 
        { 
            let mut line = String::new(); 
            stdin().read_line(&mut line).unwrap(); 
            line.split_whitespace().map(|t|t.parse::<$t>().unwrap()).collect::<Vec<_>>()
        }
    };
    ([$t: ty];$n: expr) => {
        (0..$n).map(|_|get!([$t])).collect::<Vec<_>>()
    };
    ($t: ty) => {
        {
            let mut line = String::new();
            stdin().read_line(&mut line).unwrap();
            line.trim().parse::<$t>().unwrap()
        }
    };
    ($($t: ty),*) => {
        { 
            let mut line = String::new();
            stdin().read_line(&mut line).unwrap();
            let mut iter = line.split_whitespace();
            ($(iter.next().unwrap().parse::<$t>().unwrap(),)*)
        }
    };
    ($t: ty; $n: expr) => {
        (0..$n).map(|_|get!($t)).collect::<Vec<_>>()
    };
    ($($t: ty),*; $n: expr) => {
        (0..$n).map(|_|get!($($t),*)).collect::<Vec<_>>()
    };
}

#[allow(unused_macros)]
macro_rules! debug {
    ($($a:expr),*) => {
        #[cfg(debug_assertions)]
        writeln!(&mut std::io::stderr(), concat!("[DEBUG] ", $(stringify!($a), "={:?} "),*), $($a),*).unwrap();
    }
}

const BIG_STACK_SIZE: bool = true;

#[allow(dead_code)]
fn main() {
    use std::thread;
    if BIG_STACK_SIZE {
        thread::Builder::new()
            .stack_size(32 * 1024 * 1024)
            .name("solve".into())
            .spawn(solve)
            .unwrap()
            .join()
            .unwrap();
    } else {
        solve();
    }
}

pub struct UnionFindRank {
    parent: Vec<usize>,
    rank: Vec<usize>,
}
impl UnionFindRank {
#[allow(dead_code)]
    pub fn new(n: usize) -> Self {
        let mut parent = vec![0; n];
        for i in 0..n {
            parent[i] = i;
        }
        UnionFindRank {
            parent: parent,
            rank: vec![0; n],
        }
    }
#[allow(dead_code)]
    pub fn root(&mut self, a: usize) -> usize {
        if self.parent[a] == a {
            a
        } else {
            let tmp = self.parent[a];
            self.parent[a] = self.root(tmp);
            self.parent[a]
        }
    }
#[allow(dead_code)]
    pub fn unite(&mut self, a: usize, b: usize) {
        let a = self.root(a);
        let b = self.root(b);
        if a == b {
            return;
        }
        if self.rank[a] > self.rank[b] {
            self.parent[b] = a;
        } else {
            self.parent[a] = b;
            if self.rank[a] == self.rank[b] {
                self.rank[b] += 1;
            }
        }
    }
#[allow(dead_code)]
    pub fn is_same(&mut self, a: usize, b: usize) -> bool {
        self.root(a) == self.root(b)
    }
}

fn solve() {
    let n = get!(usize);
    let xy = get!(usize, usize; n).into_iter().enumerate().collect::<Vec<_>>();
    let mut xyx = xy.clone();
    let mut xyy = xy;
    xyx.sort_by_key(|e| (e.1).0);
    xyy.sort_by_key(|e| (e.1).1);
    let mut vec = xyx.iter().zip(xyx.iter().skip(1)).map(|(&(i1,(x1,_)), &(i2,(x2,_)))| (x2-x1, (i1,i2))).collect::<Vec<_>>();
    vec.extend(xyy.iter().zip(xyy.iter().skip(1)).map(|(&(i1,(_,y1)), &(i2,(_,y2)))| (y2-y1, (i1,i2))).collect::<Vec<_>>());
    vec.sort_by_key(|e| e.0);
    let mut tree = UnionFindRank::new(n+1);
    let mut sum = 0;
    for (cost, (v1,v2)) in vec {
        if !tree.is_same(v1,v2) {
            tree.unite(v1,v2);
            sum += cost;
        }
    }
    println!("{}", sum);
}


Measured memory_bytes: 30972