Problem:
Score : 500 points

Problem Statement

There are N towns on a plane. The i-th town is located at the coordinates (x_i,y_i). There may be more than one town at the same coordinates.

You can build a road between two towns at coordinates (a,b) and (c,d) for a cost of min(|a-c|,|b-d|) yen (the currency of Japan). It is not possible to build other types of roads.

Your objective is to build roads so that it will be possible to travel between every pair of towns by traversing roads. At least how much money is necessary to achieve this?

Constraints

2 ≤ N ≤ 10^5

0 ≤ x_i,y_i ≤ 10^9

All input values are integers.

Input

Input is given from Standard Input in the following format:

N
x_1 y_1
x_2 y_2
:
x_N y_N

Output

Print the minimum necessary amount of money in order to build roads so that it will be possible to travel between every pair of towns by traversing roads.

Sample Input 1

3
1 5
3 9
7 8

Sample Output 1

3

Build a road between Towns 1 and 2, and another between Towns 2 and 3. The total cost is 2+1=3 yen.

Sample Input 2

6
8 3
4 9
12 19
18 1
13 5
7 6

Sample Output 2

8

Solution in Rust (1.42.0) (judge verdict: Accepted)

#[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()
    }
}