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# (.NET Core 3.1.201) (judge verdict: Accepted)

using System;
using System.IO;
using System.Collections.Generic;
using System.Linq;
using System.Numerics;
using System.Runtime.CompilerServices;

namespace FertiLib.Contest.A
{
	static class Program
	{
		public static void Solve(Scanner cin)
		{
			int n = cin.ReadInt();
			var (x, y) = cin.ReadValueArray<int, int>(n);
			var xset = new Set<(int x, int i)>();
			var yset = new Set<(int y, int i)>();
			for (int i = 0; i < n; i++)
			{
				xset.Add((x[i], i));
				yset.Add((y[i], i));
			}
			var pq = new PriorityQueue<(long len, int index1, int index2)>();
			var uf = new UnionFind(n);
			for (int i = 1; i < n; i++)
			{
				pq.Enqueue((xset[i].x - xset[i - 1].x, xset[i].i, xset[i - 1].i));
				pq.Enqueue((yset[i].y - yset[i - 1].y, yset[i].i, yset[i - 1].i));
			}
			int con = 0;
			long ans = 0;
			while (con < n - 1)
			{
				var (nlen, nx, ny) = pq.Dequeue();
				if (!uf.IsSame(nx, ny))
				{
					uf.Unite(nx, ny);
					ans += nlen;
					con++;
				}
			}
			Console.WriteLine(ans);
		}

		public static void Main(string[] args)
		{
			var sw = new StreamWriter(Console.OpenStandardOutput()) { AutoFlush = false };
			Console.SetOut(sw);
			var cin = new Scanner();
			Solve(cin);
			Console.Out.Flush();
		}

		public static void YESNO(bool condition) => Console.WriteLine(condition ? "YES" : "NO");
		public static void YesNo(bool condition) => Console.WriteLine(condition ? "Yes" : "No");
		public static void yesno(bool condition) => Console.WriteLine(condition ? "yes" : "no");

		public static bool Chmax<T>(ref T a, T b) where T : IComparable<T>
		{
			if (a.CompareTo(b) >= 0) return false;
			a = b;
			return true;
		}
		public static bool Chmin<T>(ref T a, T b) where T : IComparable<T>
		{
			if (a.CompareTo(b) <= 0) return false;
			a = b;
			return true;
		}
	}

	public class UnionFind
	{
		public int Count { get; private set; }
		int[] parent;
		int[] depth;

		public UnionFind(int n)
		{
			parent = Enumerable.Range(0, n).ToArray();
			depth = Enumerable.Repeat(0, n).ToArray();
		}

		public void Unite(int x, int y)
		{
			x = Find(x);
			y = Find(y);
			if (x == y) return;
			if (depth[x] > depth[y])
			{
				parent[y] = x;
			}
			else
			{
				parent[x] = y;
				if (depth[x] == depth[y]) depth[x]++;
			}
		}

		public int Find(int x)
		{
			if (parent[x] == x) return x;
			else return parent[x] = Find(parent[x]);
		}

		public bool IsSame(int x, int y) => Find(x) == Find(y);
	}

	public class PriorityQueue<T> : IEnumerable<T>
	{
		private readonly List<T> heap;
		private readonly IComparer<T> comparer;

		public PriorityQueue(IComparer<T> comparer)
		{
			this.comparer = comparer;
			this.heap = new List<T>();
		}

		public PriorityQueue(Comparison<T> comparison) : this(Comparer<T>.Create(comparison)) { }

		public PriorityQueue() : this(Comparer<T>.Default) { }

		public void Enqueue(T item)
		{
			this.heap.Add(item);
			int index = this.Count - 1;
			while (index > 0)
			{
				var par = Parent(index);
				if (comparer.Compare(heap[index], heap[par]) >= 0) break;
				Swap(index, par);
				index = par;
			}
		}

		public T Dequeue()
		{
			var ret = this.Peek;
			var last = this.Count - 1;
			heap[0] = heap[last];
			heap.RemoveAt(last--);
			var index = 0;
			while (true)
			{
				var (r, l) = Child(index);
				int child;
				if (l <= last)
				{
					if (comparer.Compare(heap[l], heap[r]) < 0) child = l;
					else child = r;
				}
				else if (r <= last) child = r;
				else break;
				if (comparer.Compare(heap[index], heap[child]) <= 0) break;
				Swap(index, child);
				index = child;
			}
			return ret;
		}

		public T Peek => heap[0];

		public int Count => heap.Count;

		private void Swap(int a, int b)
		{
			var t = heap[a];
			heap[a] = heap[b];
			heap[b] = t;
		}

		private int Parent(int index) => (index - 1) / 2;

		private (int l, int r) Child(int index) => (2 * index + 1, 2 * index + 2);

		public IEnumerator<T> GetEnumerator()
		{
			var ret = new List<T>();
			while (this.Count > 0)
			{
				ret.Add(this.Dequeue());
			}

			for (int i = 0; i < ret.Count; i++)
			{
				this.Enqueue(ret[i]);
			}

			foreach (var e in ret)
			{
				yield return e;
			}
		}

		System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() => GetEnumerator();
	}

	public class Set<T> : IEnumerable<T> where T : IComparable<T>
	{
		Node root;
		readonly IComparer<T> comparer;
		readonly Node nil;
		public bool IsMultiSet { get; set; }

		public Set() : this(Comparer<T>.Default) { }
		public Set(IComparer<T> comparer)
		{
			nil = new Node(default);
			root = nil;
			this.comparer = comparer;
		}
		public Set(Comparison<T> comparison) : this(Comparer<T>.Create(comparison)) { }

		public T this[int index]
		{
			get
			{
				if (index < 0 || root.Count < index) throw new ArgumentOutOfRangeException();
				return Find(root, index);
			}
		}

		public bool Add(T x) => Insert(ref root, x);
		public bool Remove(T x) => Erase(ref root, x);
		public void RemoveAt(int index)
		{
			if (index < 0 || Count < index) throw new ArgumentOutOfRangeException();
			EraseAt(ref root, index);
		}
		public bool Contains(T x) => this.Count == 0 ? false : EqualRange(x) > 0;
		public int LowerBound(T x) => BinarySearch(root, x, false);
		public int UpperBound(T x) => BinarySearch(root, x, true);
		public int EqualRange(T x) => UpperBound(x) - LowerBound(x);

		public void Clear() => root = nil;

		public T Min() => root.Min.Value;
		public T Max() => root.Max.Value;

		public T[] Items
		{
			get
			{
				var a = new T[root.Count];
				var k = 0;
				Walk(root, a, ref k);
				return a;
			}
		}
		public int Count => root.Count;
		public int Height => root.Height;

		public IEnumerator<T> GetEnumerator() { return Items.AsEnumerable().GetEnumerator(); }
		System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() => GetEnumerator();

		bool Insert(ref Node p, T x)
		{
			if (p.Count == 0)
			{
				p = new Node(x);
				p.Left = p.Right = nil;
				p.Update();
				return true;
			}
			bool ret;
			var t = comparer.Compare(p.Value, x);
			if (t > 0)
			{
				ret = Insert(ref p.Left, x);
			}
			else if (t < 0)
			{
				ret = Insert(ref p.Right, x);
			}
			else
			{
				if (IsMultiSet == true) ret = Insert(ref p.Left, x);
				else return false;
			}
			Balance(ref p);
			return ret;
		}

		bool Erase(ref Node p, T x)
		{
			if (p.Count == 0) return false;
			var t = comparer.Compare(p.Value, x);
			bool ret;
			if (t < 0) ret = Erase(ref p.Right, x);
			else if (t > 0) ret = Erase(ref p.Left, x);
			else
			{
				ret = true;
				if (p.Right.Count == 0) { p = p.Left; return true; }
				if (p.Left.Count == 0) { p = p.Right; return true; }

				p.Value = p.Left.Max.Value;
				Erase(ref p.Left, p.Left.Max.Value);
			}
			Balance(ref p);

			return ret;
		}

		void EraseAt(ref Node p, int index)
		{
			var count = p.Left.Count;
			if (index < count) EraseAt(ref p.Left, index);
			else if (index > count) EraseAt(ref p.Right, index - count - 1);
			else
			{
				if (p.Left.Count == 0) { p = p.Right; return; }
				if (p.Right.Count == 0) { p = p.Left; return; }

				p.Value = p.Left.Max.Value;
				EraseAt(ref p.Left, index - 1);
			}

			Balance(ref p);
		}

		void Walk(Node t, T[] a, ref int k)
		{
			if (t.Count == 0) return;
			Walk(t.Left, a, ref k);
			a[k++] = t.Value;
			Walk(t.Right, a, ref k);
		}

		void Balance(ref Node p)
		{
			var balance = p.Left.Height - p.Right.Height;
			if (balance < -1)
			{
				if (p.Right.Left.Height - p.Right.Right.Height > 0) RotateR(ref p.Right);
				RotateL(ref p);
			}
			else if (balance > 1)
			{
				if (p.Left.Left.Height - p.Left.Right.Height < 0) RotateL(ref p.Left);
				RotateR(ref p);
			}
			else p.Update();
		}

		T Find(Node p, int index)
		{
			if (index < p.Left.Count) return Find(p.Left, index);
			if (index > p.Left.Count) return Find(p.Right, index - p.Left.Count - 1);
			return p.Value;
		}

		void RotateL(ref Node p)
		{
			var r = p.Right;
			p.Right = r.Left;
			r.Left = p;
			p.Update();
			r.Update();
			p = r;
		}

		void RotateR(ref Node p)
		{
			var l = p.Left;
			p.Left = l.Right;
			l.Right = p;
			p.Update();
			l.Update();
			p = l;
		}

		int BinarySearch(Node p, T x, bool isUpperBound)
		{
			if (p.Count == 0) throw new NullReferenceException();

			var node = p;

			var ret = 0;

			while (p.Count != 0)
			{
				var cmp = p.Value.CompareTo(x);
				if (cmp > 0 || (!isUpperBound && cmp == 0))
				{
					p = p.Left;
				}
				else
				{
					ret += p.Left.Count + 1;
					p = p.Right;
				}
			}

			return ret;
		}

		public override string ToString()
		{
			return string.Join(", ", Items);
		}

		class Node
		{
			public Node Left, Right;
			public T Value { get; set; }

			public int Count { get; private set; }
			public int Height { get; private set; }

			public Node Min
			{
				get
				{
					if (Left.Count == 0) return this;
					else return Left.Min;
				}
			}

			public Node Max
			{
				get
				{
					if (Right.Count == 0) return this;
					else return Right.Max;
				}
			}

			public Node(T value) => Value = value;

			public void Update()
			{
				Count = Left.Count + Right.Count + 1;
				Height = Math.Max(Left.Height, Right.Height) + 1;
			}

			public override string ToString() => $"Count = {Count}, Value = {Value}";
		}
	}

	static class Extention
	{
		public static string Join<T>(this IEnumerable<T> x, string separator = "") => string.Join(separator, x);

		public static int UpperBound<T>(this IList<T> list, T value) => list.BinarySearch(value, true, 0, list.Count, Comparer<T>.Default);
		public static int LowerBound<T>(this IList<T> list, T value) => list.BinarySearch(value, false, 0, list.Count, Comparer<T>.Default);
		public static int BinarySearch<T>(this IList<T> list, T value, bool isUpperBound, int index, int length, Comparer<T> comparer)
		{
			var ng = index - 1;
			var ok = index + length;
			while (ok - ng > 1)
			{
				var mid = ng + (ok - ng) / 2;
				var res = comparer.Compare(list[mid], value);
				if (res < 0 || (isUpperBound && res == 0)) ng = mid;
				else ok = mid;
			}
			return ok;
		}
	}

	class Scanner
	{
		string[] s;
		int i;

		char[] separator = new char[] { ' ' };

		public Scanner()
		{
			s = new string[0];
			i = 0;
		}

		public string Read() => ReadString();

		public string ReadString()
		{
			if (i < s.Length) return s[i++];
			string st = Console.ReadLine();
			while (st == "") st = Console.ReadLine();
			s = st.Split(separator, StringSplitOptions.RemoveEmptyEntries);
			if (s.Length == 0) return ReadString();
			i = 0;
			return s[i++];
		}

		public string[] ReadStringArray(int N)
		{
			string[] Array = new string[N];
			for (int i = 0; i < N; i++)
			{
				Array[i] = ReadString();
			}
			return Array;
		}

		public int ReadInt()
		{
			return int.Parse(ReadString());
		}

		public int[] ReadIntArray(int N, int add = 0)
		{
			int[] Array = new int[N];
			for (int i = 0; i < N; i++)
			{
				Array[i] = ReadInt() + add;
			}
			return Array;
		}

		public long ReadLong()
		{
			return long.Parse(ReadString());
		}

		public long[] ReadLongArray(int N, long add = 0)
		{
			long[] Array = new long[N];
			for (int i = 0; i < N; i++)
			{
				Array[i] = ReadLong() + add;
			}
			return Array;
		}

		public double ReadDouble()
		{
			return double.Parse(ReadString());
		}

		public double[] ReadDoubleArray(int N, double add = 0)
		{
			double[] Array = new double[N];
			for (int i = 0; i < N; i++)
			{
				Array[i] = ReadDouble() + add;
			}
			return Array;
		}

		public T1 ReadValue<T1>() => (T1)Convert.ChangeType(ReadString(), typeof(T1));

		public (T1, T2) ReadValue<T1, T2>()
		{
			var inputs = ReadStringArray(2);
			var v1 = (T1)Convert.ChangeType(inputs[0], typeof(T1));
			var v2 = (T2)Convert.ChangeType(inputs[1], typeof(T2));
			return (v1, v2);
		}

		public (T1, T2, T3) ReadValue<T1, T2, T3>()
		{
			var inputs = ReadStringArray(3);
			var v1 = (T1)Convert.ChangeType(inputs[0], typeof(T1));
			var v2 = (T2)Convert.ChangeType(inputs[1], typeof(T2));
			var v3 = (T3)Convert.ChangeType(inputs[2], typeof(T3));
			return (v1, v2, v3);
		}

		public (T1, T2, T3, T4) ReadValue<T1, T2, T3, T4>()
		{
			var inputs = ReadStringArray(4);
			var v1 = (T1)Convert.ChangeType(inputs[0], typeof(T1));
			var v2 = (T2)Convert.ChangeType(inputs[1], typeof(T2));
			var v3 = (T3)Convert.ChangeType(inputs[2], typeof(T3));
			var v4 = (T4)Convert.ChangeType(inputs[3], typeof(T4));
			return (v1, v2, v3, v4);
		}

		public (T1, T2, T3, T4, T5) ReadValue<T1, T2, T3, T4, T5>()
		{
			var inputs = ReadStringArray(5);
			var v1 = (T1)Convert.ChangeType(inputs[0], typeof(T1));
			var v2 = (T2)Convert.ChangeType(inputs[1], typeof(T2));
			var v3 = (T3)Convert.ChangeType(inputs[2], typeof(T3));
			var v4 = (T4)Convert.ChangeType(inputs[3], typeof(T4));
			var v5 = (T5)Convert.ChangeType(inputs[4], typeof(T5));
			return (v1, v2, v3, v4, v5);
		}

		public (T1, T2, T3, T4, T5, T6) ReadValue<T1, T2, T3, T4, T5, T6>()
		{
			var inputs = ReadStringArray(6);
			var v1 = (T1)Convert.ChangeType(inputs[0], typeof(T1));
			var v2 = (T2)Convert.ChangeType(inputs[1], typeof(T2));
			var v3 = (T3)Convert.ChangeType(inputs[2], typeof(T3));
			var v4 = (T4)Convert.ChangeType(inputs[3], typeof(T4));
			var v5 = (T5)Convert.ChangeType(inputs[4], typeof(T5));
			var v6 = (T6)Convert.ChangeType(inputs[5], typeof(T6));
			return (v1, v2, v3, v4, v5, v6);
		}

		public (T1, T2, T3, T4, T5, T6, T7) ReadValue<T1, T2, T3, T4, T5, T6, T7>()
		{
			var inputs = ReadStringArray(7);
			var v1 = (T1)Convert.ChangeType(inputs[0], typeof(T1));
			var v2 = (T2)Convert.ChangeType(inputs[1], typeof(T2));
			var v3 = (T3)Convert.ChangeType(inputs[2], typeof(T3));
			var v4 = (T4)Convert.ChangeType(inputs[3], typeof(T4));
			var v5 = (T5)Convert.ChangeType(inputs[4], typeof(T5));
			var v6 = (T6)Convert.ChangeType(inputs[5], typeof(T6));
			var v7 = (T7)Convert.ChangeType(inputs[6], typeof(T7));
			return (v1, v2, v3, v4, v5, v6, v7);
		}

		public T1[] ReadValueArray<T1>(int N)
		{
			var v1 = new T1[N];
			for (int i = 0; i < N; i++)
			{
				v1[i] = ReadValue<T1>();
			}
			return v1;
		}

		public (T1[], T2[]) ReadValueArray<T1, T2>(int N)
		{
			var (v1, v2) = (new T1[N], new T2[N]);
			for (int i = 0; i < N; i++)
			{
				var (t1, t2) = ReadValue<T1, T2>();
				v1[i] = t1;
				v2[i] = t2;
			}
			return (v1, v2);
		}

		public (T1[], T2[], T3[]) ReadValueArray<T1, T2, T3>(int N)
		{
			var (v1, v2, v3) = (new T1[N], new T2[N], new T3[N]);
			for (int i = 0; i < N; i++)
			{
				var (t1, t2, t3) = ReadValue<T1, T2, T3>();
				v1[i] = t1;
				v2[i] = t2;
				v3[i] = t3;
			}
			return (v1, v2, v3);
		}

		public (T1[], T2[], T3[], T4[]) ReadValueArray<T1, T2, T3, T4>(int N)
		{
			var (v1, v2, v3, v4) = (new T1[N], new T2[N], new T3[N], new T4[N]);
			for (int i = 0; i < N; i++)
			{
				var (t1, t2, t3, t4) = ReadValue<T1, T2, T3, T4>();
				v1[i] = t1;
				v2[i] = t2;
				v3[i] = t3;
				v4[i] = t4;
			}
			return (v1, v2, v3, v4);
		}

		public (T1[], T2[], T3[], T4[], T5[]) ReadValueArray<T1, T2, T3, T4, T5>(int N)
		{
			var (v1, v2, v3, v4, v5) = (new T1[N], new T2[N], new T3[N], new T4[N], new T5[N]);
			for (int i = 0; i < N; i++)
			{
				var (t1, t2, t3, t4, t5) = ReadValue<T1, T2, T3, T4, T5>();
				v1[i] = t1;
				v2[i] = t2;
				v3[i] = t3;
				v4[i] = t4;
				v5[i] = t5;
			}
			return (v1, v2, v3, v4, v5);
		}

		public (T1[], T2[], T3[], T4[], T5[], T6[]) ReadValueArray<T1, T2, T3, T4, T5, T6>(int N)
		{
			var (v1, v2, v3, v4, v5, v6) = (new T1[N], new T2[N], new T3[N], new T4[N], new T5[N], new T6[N]);
			for (int i = 0; i < N; i++)
			{
				var (t1, t2, t3, t4, t5, t6) = ReadValue<T1, T2, T3, T4, T5, T6>();
				v1[i] = t1;
				v2[i] = t2;
				v3[i] = t3;
				v4[i] = t4;
				v5[i] = t5;
				v6[i] = t6;
			}
			return (v1, v2, v3, v4, v5, v6);
		}

		public (T1[], T2[], T3[], T4[], T5[], T6[], T7[]) ReadValueArray<T1, T2, T3, T4, T5, T6, T7>(int N)
		{
			var (v1, v2, v3, v4, v5, v6, v7) = (new T1[N], new T2[N], new T3[N], new T4[N], new T5[N], new T6[N], new T7[N]);
			for (int i = 0; i < N; i++)
			{
				var (t1, t2, t3, t4, t5, t6, t7) = ReadValue<T1, T2, T3, T4, T5, T6, T7>();
				v1[i] = t1;
				v2[i] = t2;
				v3[i] = t3;
				v4[i] = t4;
				v5[i] = t5;
				v6[i] = t6;
				v7[i] = t7;
			}
			return (v1, v2, v3, v4, v5, v6, v7);
		}
	}
}