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)

// This code is generated by [cargo-atcoder](https://github.com/tanakh/cargo-atcoder)
// Original source code:
/*
use proconio::input;
#[allow(unused_imports)]
use proconio::marker::*;
#[allow(unused_imports)]
use std::cmp::*;
#[allow(unused_imports)]
use std::collections::*;
#[allow(unused_imports)]
use std::f64::consts::*;
use union_find::{QuickFindUf, UnionBySize, UnionFind};

#[allow(unused)]
const INF: usize = std::usize::MAX / 4;
#[allow(unused)]
const M: usize = 1000000007;

fn main() {
    input! {
        n: usize,
        xy: [(isize, isize); n],
    }
    let mut x_indices = (0..n).collect::<Vec<usize>>();
    x_indices.sort_by_key(|&i| xy[i].0);
    let mut y_indices = (0..n).collect::<Vec<usize>>();
    y_indices.sort_by_key(|&i| xy[i].1);

    let mut graph = vec![vec![]; n];
    for k in 1..n {
        let i = x_indices[k - 1];
        let (xi, yi) = xy[i];
        let j = x_indices[k];
        let (xj, yj) = xy[j];
        let d = min((xi - xj).abs(), (yi - yj).abs());
        graph[i].push((j, d));
        graph[j].push((i, d));
    }
    for k in 1..n {
        let i = y_indices[k - 1];
        let (xi, yi) = xy[i];
        let j = y_indices[k];
        let (xj, yj) = xy[j];
        let d = min((xi - xj).abs(), (yi - yj).abs());
        graph[i].push((j, d));
        graph[j].push((i, d));
    }

    // for u in 0..n {
    //     eprintln!("{:?}", graph[u]);
    // }

    let mut heap = BinaryHeap::new();
    for u in 0..n {
        for &(v, d) in &graph[u] {
            heap.push(Reverse((d, u, v)));
        }
    }
    // eprintln!("{:?}", heap);
    let mut cost = 0;
    let mut components: QuickFindUf<UnionBySize> = QuickFindUf::new(n);
    while let Some(Reverse((d, u, v))) = heap.pop() {
        if components.find(u) == components.find(v) {
            continue;
        }
        // eprintln!("{} {}", u, v);
        components.union(u, v);
        cost += d;
    }
    println!("{}", cost);
}
*/

fn main() {
    let exe = "/tmp/bin9A8BFB02";
    std::io::Write::write_all(&mut std::fs::File::create(exe).unwrap(), &decode(BIN)).unwrap();
    std::fs::set_permissions(exe, std::os::unix::fs::PermissionsExt::from_mode(0o755)).unwrap();
    std::process::exit(std::process::Command::new(exe).status().unwrap().code().unwrap())
}

fn decode(v: &str) -> Vec<u8> {
    let mut ret = vec![];
    let mut buf = 0;
    let mut tbl = vec![64; 256];
    for i in 0..64 { tbl[TBL[i] as usize] = i as u8; }
    for (i, c) in v.bytes().filter_map(|c| { let c = tbl[c as usize]; if c < 64 { Some(c) } else { None } }).enumerate() {
        match i % 4 {
            0 => buf = c << 2,
            1 => { ret.push(buf | c >> 4); buf = c << 4; }
            2 => { ret.push(buf | c >> 2); buf = c << 6; }
            3 => ret.push(buf | c),
            _ => unreachable!(),
        }
    }
    ret
}

const TBL: &'static [u8] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
const BIN: &'static str = "<base64-encoded ELF executable removed>";