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 C# (Mono 4.6.2.0) (judge verdict: Accepted)

using System;
using System.Collections.Generic;
using System.Linq;
using System.IO;
using static System.Console;
using static System.Convert;
using static System.Math;
//using static System.Globalization.CultureInfo;
using System.Text;
class Program
{
    private static void chmin<T>(ref T num, T val) where T : IComparable<T>
        => num = num.CompareTo(val) == 1 ? val : num;
    private static void chmax<T>(ref T num, T val) where T : IComparable<T>
        => num = num.CompareTo(val) == -1 ? val : num;
    private static void swap<T>(ref T v1,ref T v2)
    { var t = v2;v2 = v1;v1 = t; }
    static void Main(string[] args)
    {
        var pr = new Program();
        var sw = new StreamWriter(Console.OpenStandardOutput()) { AutoFlush = false };
        Console.SetOut(sw);
        pr.Solve();
        Console.Out.Flush();
    }
    void Solve()
    {
        var num = Input.num;
        var xy = new Pair<int, int, int>[num];
        for(var i = 0; i < num; i++)
            xy[i] = new Pair<int, int, int>(i, Input.Next<int>(), Input.Next<int>());
        var sx = xy.OrderBy(v => v.v2).ToArray();
        var sy = xy.OrderBy(v => v.v3).ToArray();
        Func<int, int[], Pair<long, int>[]> func = (a, b) =>
           {
               var ps = Enumerable.Repeat(0, a).Select(_ => new Pair<long, int>(long.MaxValue, -1)).ToArray();
               for (var i = 0; i < num - 1; i++)
               {
                   if (b[sx[i].v1] == b[sx[i + 1].v1]) goto SECOND;
                   long w = sx[i + 1].v2 - sx[i].v2;
                   if (ps[b[sx[i].v1]].v1 > w)
                       ps[b[sx[i].v1]] = new Pair<long, int>(w, b[sx[i + 1].v1]);
                   if (ps[b[sx[i + 1].v1]].v1 > w)
                       ps[b[sx[i + 1].v1]] = new Pair<long, int>(w, b[sx[i].v1]);
                   SECOND:;
                   if (b[sy[i].v1] == b[sy[i + 1].v1]) continue;
                   w = sy[i + 1].v3 - sy[i].v3;
                   if (ps[b[sy[i].v1]].v1 > w)
                       ps[b[sy[i].v1]] = new Pair<long, int>(w, b[sy[i + 1].v1]);
                   if (ps[b[sy[i + 1].v1]].v1 > w)
                       ps[b[sy[i + 1].v1]] = new Pair<long, int>(w, b[sy[i].v1]);
               }
               return ps;
           };
        WriteLine(Boruvka(num, func));
    }
    public static long Boruvka(int num, Func<int, int[], Pair<long, int>[]> func)
    {
        var uf = new UnionFind(num);
        var res = 0L;
        var rev = new int[num];
        var parent = new int[num];
        while (true)
        {
            //var update = false;
            var c = 0;
            for (var i = 0; i < num; i++)
                if (i == uf.Parent(i))
                {
                    rev[c] = i;
                    parent[i] = c++;
                }
            for (var i = 0; i < num; i++)
                parent[i] = parent[uf.Parent(i)];
            var pair = func(c, parent);
            for (var i = 0; i < c; i++)
                if (pair[i].v2 != -1 && !uf.IsSame(rev[pair[i].v2], rev[i]))
                {
                    uf.Union(rev[pair[i].v2], rev[i]);
                    res += pair[i].v1;
                }
            if (uf.IndependenceNum==1) break;
        }
        return res;
    }
}

public class UnionFind
{
    private int[] _parent, _size, _rank;
    public UnionFind(int num)
    {
        IndependenceNum = num;
        _parent = new int[num]; _size = new int[num]; _rank = new int[num];
        for (var i = 0; i < num; i++) { _parent[i] = i; _size[i] = 1; }
    }
    //独立な集合の数
    public int IndependenceNum { get; private set; }
    private int Find(int i)
        => i == _parent[i] ? i : (_parent[i] = Find(_parent[i]));
    public int Parent(int i)
        => Find(i);
    public int Size(int i)
        => _size[Find(i)];
    public bool Union(int v1, int v2)
    {
        v1 = Find(v1); v2 = Find(v2);
        if (v1 == v2) return false;
        IndependenceNum--;
        if (_rank[v1] > _rank[v2])
        {
            _parent[v2] = v1;
            _size[v1] += _size[v2];
        }
        else
        {
            _parent[v1] = v2;
            _size[v2] += _size[v1];
            if (_rank[v1] == _rank[v2])
                _rank[v2]++;
        }
        return true;
    }
    public bool IsSame(int v1, int v2)
        => Find(v1) == Find(v2);
}


public class Input
{
    public static string read => ReadLine().Trim();
    public static int[] ar => read.Split(' ').Select(int.Parse).ToArray();
    public static int num => ToInt32(read);
    public static long[] arL => read.Split(' ').Select(long.Parse).ToArray();
    public static long numL => ToInt64(read);
    public static T[] create<T>(int n, Func<int, T> f)
        => Enumerable.Repeat(0, n).Select(f).ToArray();
    public static char[][] grid(int h)
        => create(h, _ => read.ToCharArray());
    public static int[] ar1D(int n)
        => create(n, _ => num);
    public static long[] arL1D(int n)
        => create(n, _ => numL);
    public static string[] strs(int n)
        => create(n, _ => read);
    public static int[][] ar2D(int n)
        => create(n, _ => ar);
    public static long[][] arL2D(int n)
        => create(n, _ => arL);
    public static List<T>[] edge<T>(int n)
        => create(n, _ => new List<T>());
    public static T GetValue<T>(string g)
    {
        var t = typeof(T);
        if (t == typeof(int))
            return (T)(object)int.Parse(g);
        if (t == typeof(long))
            return (T)(object)long.Parse(g);
        if (t == typeof(string))
            return (T)(object)g;
        if (t == typeof(char))
            return (T)(object)char.Parse(g);
        if (t == typeof(double))
            return (T)(object)double.Parse(g);
        if (t == typeof(bool))
            return (T)(object)bool.Parse(g);
        return default(T);
    }
    public static void Make<T1, T2>(out T1 v1, out T2 v2)
    {
        v1 = Next<T1>();
        v2 = Next<T2>();
    }
    public static void Make<T1, T2, T3>(out T1 v1, out T2 v2, out T3 v3)
    {
        Make(out v1, out v2);
        v3 = Next<T3>();
    }
    public static void Make<T1, T2, T3, T4>(out T1 v1, out T2 v2, out T3 v3, out T4 v4)
    {
        Make(out v1, out v2, out v3);
        v4 = Next<T4>();
    }
    public static void Make<T1, T2, T3, T4, T5>(out T1 v1, out T2 v2, out T3 v3, out T4 v4, out T5 v5)
    {
        Make(out v1, out v2, out v3, out v4);
        v5 = Next<T5>();
    }
    public static void Make<T1, T2, T3, T4, T5, T6>(out T1 v1, out T2 v2, out T3 v3, out T4 v4, out T5 v5, out T6 v6)
    {
        Make(out v1, out v2, out v3, out v4, out v5);
        v6 = Next<T6>();
    }
    private static Queue<string> sc;
    public static T Next<T>(){ sc = sc ?? new Queue<string>(); if (sc.Count == 0) foreach (var item in read.Split(' ')) sc.Enqueue(item);return GetValue<T>(sc.Dequeue()); }
    public static void Next<T>(ref T val) => val = Next<T>(); 
    public const long Inf = (long)1e18;
    public const double eps = 1e-6;
    public const string Alfa = "abcdefghijklmnopqrstuvwxyz";
    public const int MOD = 1000000007;
}

public class Pair<T1, T2> : IComparable<Pair<T1, T2>>
{
    public T1 v1 { get; set; }
    public T2 v2 { get; set; }
    public Pair() { v1 = Input.Next<T1>(); v2 = Input.Next<T2>(); }
    public Pair(T1 v1, T2 v2)
    { this.v1 = v1; this.v2 = v2; }

    public int CompareTo(Pair<T1, T2> p)
    {
        var c = Comparer<T1>.Default.Compare(v1, p.v1);
        if (c == 0)
            c = Comparer<T2>.Default.Compare(v2, p.v2);
        return c;
    }
    public override string ToString()
        => $"{v1.ToString()} {v2.ToString()}";
    public override bool Equals(object obj)
        => this == (Pair<T1, T2>)obj;
    public override int GetHashCode()
        => v1.GetHashCode() ^ v2.GetHashCode();
    public static bool operator ==(Pair<T1, T2> p1, Pair<T1, T2> p2)
        => p1.CompareTo(p2) == 0;
    public static bool operator !=(Pair<T1, T2> p1, Pair<T1, T2> p2)
        => p1.CompareTo(p2) != 0;
    public static bool operator >(Pair<T1, T2> p1, Pair<T1, T2> p2)
        => p1.CompareTo(p2) == 1;
    public static bool operator >=(Pair<T1, T2> p1, Pair<T1, T2> p2)
        => p1.CompareTo(p2) != -1;
    public static bool operator <(Pair<T1, T2> p1, Pair<T1, T2> p2)
        => p1.CompareTo(p2) == -1;
    public static bool operator <=(Pair<T1, T2> p1, Pair<T1, T2> p2)
        => p1.CompareTo(p2) != 1;
}

public class Pair<T1, T2, T3> : Pair<T1, T2>, IComparable<Pair<T1, T2, T3>>
{
    public T3 v3 { get; set; }
    public Pair() : base() { v3 = Input.Next<T3>(); }
    public Pair(T1 v1, T2 v2, T3 v3) : base(v1, v2)
    { this.v3 = v3; }

    public int CompareTo(Pair<T1, T2, T3> p)
    {
        var c = base.CompareTo(p);
        if (c == 0)
            c = Comparer<T3>.Default.Compare(v3, p.v3);
        return c;
    }
    public override string ToString()
        => $"{base.ToString()} {v3.ToString()}";
}