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)

use std::io::Read;

struct Edge {
    from: usize,
    to: usize,
    cost: i64,
}
impl Ord for Edge {
    fn cmp(&self, other: &Self) -> std::cmp::Ordering {
        self.cost.cmp(&other.cost)
    }
}
impl PartialOrd for Edge {
    fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
        Some(self.cost.cmp(&other.cost))
    }
}
impl Eq for Edge {}
impl PartialEq for Edge {
    fn eq(&self, other: &Self) -> bool {
        self.cost == other.cost
    }
}

struct DisjointSet {
    parent: Vec<usize>,
    size: Vec<usize>,
}

impl DisjointSet {
    fn new(n: usize) -> DisjointSet {
        DisjointSet {
            parent: (0..n).collect(),
            size: vec![1; n],
        }
    }
    fn root(&mut self, x: usize) -> usize {
        if x == self.parent[x] {
            x
        } else {
            let tmp = self.parent[x];
            // 根に直接繋ぐ
            self.parent[x] = self.root(tmp);
            self.parent[x]
        }
    }
    fn merge(&mut self, x: usize, y: usize) {
        let x = self.root(x);
        let y = self.root(y);
        if x == y {
            return;
        }
        if self.size[x] > self.size[y] {
            self.size[x] += self.size[y];
            self.parent[y] = x;
        } else {
            self.size[y] += self.size[x];
            self.parent[x] = y;
        }
    }
    fn same(&mut self, x: usize, y: usize) -> bool {
        self.root(x) == self.root(y)
    }

    // fn size(&mut self, x: usize) -> usize {
    //     let x = self.root(x);
    //     self.size[x]
    // }
}

fn kruskal(edges: &mut Vec<Edge>) -> i64 {
    let n: usize = edges.len();

    edges.sort();

    let mut ds = DisjointSet::new(n);
    let mut res: i64 = 0;
    for e in edges.iter() {
        if ds.same(e.from, e.to) {
            continue;
        }
        ds.merge(e.from, e.to);
        res += e.cost;
    }
    res
}

fn main() {
    let mut s = String::new();
    std::io::stdin().read_to_string(&mut s).ok();
    let mut itr = s.trim().split_whitespace();
    let n: usize = itr.next().unwrap().parse().unwrap();
    let mut xy: Vec<(i64, i64, usize)> = vec![];
    for i in 0..n {
        let x: i64 = itr.next().unwrap().parse().unwrap();
        let y: i64 = itr.next().unwrap().parse().unwrap();
        xy.push((x, y, i));
    }

    let mut edges: Vec<Edge> = Vec::new();
    xy.sort_by(|a, b| a.0.cmp(&b.0));
    for i in 1..n {
        let (from_x, from_y, from_id) = xy[i - 1];
        let (to_x, to_y, to_id) = xy[i];
        let edge = Edge {
            from: from_id,
            to: to_id,
            cost: std::cmp::min((to_x - from_x).abs(), (to_y - from_y).abs()),
        };
        edges.push(edge);
    }

    xy.sort_by(|a, b| a.1.cmp(&b.1));
    for i in 1..n {
        let (from_x, from_y, from_id) = xy[i - 1];
        let (to_x, to_y, to_id) = xy[i];
        let edge = Edge {
            from: from_id,
            to: to_id,
            cost: std::cmp::min((to_x - from_x).abs(), (to_y - from_y).abs()),
        };
        edges.push(edge);
    }
    println!("{}", kruskal(&mut edges));
}