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:
/*
#![allow(unused_imports)]
use std::cmp::*;
use std::collections::*;
use itertools::Itertools;
use proconio::{input, marker::*};
use superslice::*;
fn main() {
    input! {
        n: usize,
        towns: [(i64, i64); n],
    }
    let mut x_towns: Vec<_> = towns.iter().cloned().enumerate().map(|(i, (x, _))| (x, i)).collect();
    let mut y_towns: Vec<_> = towns.iter().cloned().enumerate().map(|(i, (_, y))| (y, i)).collect();
    x_towns.sort_unstable();
    y_towns.sort_unstable();

    let mut edges = Vec::new();
    for idx in 1..n {
        let (x2, town2) = x_towns[idx];
        let (x1, town1) = x_towns[idx-1];
        edges.push((x2-x1, town1, town2));
        let (y2, town2) = y_towns[idx];
        let (y1, town1) = y_towns[idx-1];
        edges.push((y2-y1, town1, town2));
    }
    edges.sort_unstable();

    let mut utree = UnionTree::new(n);
    let mut sum = 0;
    for (dist, town1, town2) in edges {
        if utree.unite(town1, town2) {
            sum += dist;
        }
    }

    println!("{}", sum);

}

struct UnionTree(Vec<usize>);

impl UnionTree {
    fn new(n: usize) -> Self {
        Self((0..n).collect())
    }

    fn root(&self, x: usize) -> usize {
        if x == self.0[x] {
            x
        } else {
            self.root(self.0[x])
        }
    }

    fn unite(&mut self, x: usize, y: usize) -> bool {
        let (rx, ry) = (self.root(x), self.root(y));
        if rx == ry {
            return false;
        }
        self.0[x] = rx;
        self.0[y] = rx;
        self.0[ry] = rx;
        true
    }
}
*/

fn main() {
    let exe = "/tmp/binB63C25F3";
    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>";