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;

pub type WeightedGraph = [Vec<(usize, i64)>];
pub fn prim(graph: &WeightedGraph, s: usize) -> i64 {
  let mut used = std::collections::HashSet::new();
  let mut heap = std::collections::BinaryHeap::new();

  let mut res = 0_i64;
  heap.push(std::cmp::Reverse((0_i64, s)));
  while let Some(std::cmp::Reverse((cost, u))) = heap.pop() {
    if used.contains(&u) {
      continue;
    }
    used.insert(u);
    res += cost;
    for &(v, c) in &graph[u] {
      if used.contains(&v) {
        continue;
      }
      heap.push(std::cmp::Reverse((c, v)));
    }
  }
  res
}

fn main() {
  input! {
    n: usize,
    vertexes: [(usize, usize); n]
  };

  let vertexes = vertexes
    .into_iter()
    .enumerate()
    .collect::<Vec<(usize, (usize, usize))>>();
  let mut sorted_x_vertexes = vertexes.clone();
  sorted_x_vertexes.sort_by_key(|&(_, (x, _))| x);
  let mut sorted_y_vertexes = vertexes.clone();
  sorted_y_vertexes.sort_by_key(|&(_, (_, y))| y);

  let mut graph = vec![Vec::new(); n];
  for i in 0..(n - 1) {
    let (u, (x1, _)) = sorted_x_vertexes[i];
    let (v, (x2, _)) = sorted_x_vertexes[i + 1];
    let cost = (x2 - x1) as i64;
    graph[u].push((v, cost));
    graph[v].push((u, cost));
  }
  for i in 0..(n - 1) {
    let (u, (_, y1)) = sorted_y_vertexes[i];
    let (v, (_, y2)) = sorted_y_vertexes[i + 1];
    let cost = (y2 - y1) as i64;
    graph[u].push((v, cost));
    graph[v].push((u, cost));
  }

  let res = prim(&graph, 0);
  println!("{}", res);
}
*/

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