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.15.1) (judge verdict: Accepted)

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

#[derive(Eq, PartialEq, Clone, Debug)]
pub struct Rev<T>(pub T);
impl<T: PartialOrd> PartialOrd for Rev<T> {
    fn partial_cmp(&self, other: &Rev<T>) -> Option<Ordering> {
        other.0.partial_cmp(&self.0)
    }
}
impl<T: Ord> Ord for Rev<T> {
    fn cmp(&self, other: &Rev<T>) -> Ordering {
        other.0.cmp(&self.0)
    }
}

fn solve() {
    let n = get!(usize);
    let xy = get!(isize, isize;n);

    let mut xyx = xy.into_iter().enumerate().map(|(i, (x,y))| (x,y,i)).collect::<Vec<_>>();
    let mut xyy = xyx.clone();

    xyx.sort_by_key(|e| e.0);
    xyy.sort_by_key(|e| e.1);

    let xyx = xyx.iter().zip(xyx.iter().skip(1)).map(|(&e1, &e2)| ((e1.0-e2.0).abs(), e1.2, e2.2)).collect::<Vec<_>>();
    let xyy = xyy.iter().zip(xyy.iter().skip(1)).map(|(&e1, &e2)| ((e1.1-e2.1).abs(), e1.2, e2.2)).collect::<Vec<_>>();

    let mut vij = xyx.into_iter().chain(xyy.into_iter()).collect::<Vec<_>>();
    vij.sort_by_key(|e| e.0);

    let mut uftree = UnionFindRank::new(n+1);

    let mut sum = 0;
    for (v,i,j) in vij {
        if uftree.is_same(i,j) {
            continue;
        }
        uftree.unite(i,j);
        sum += v;
    }
    println!("{}", sum);
}