import std.algorithm;
import std.range;
import std.stdio;
import std.typecons;

void main ()
{
	int n;
	while (readf (" %s", &n) > 0)
	{
		alias Point = Tuple !(int, q{x}, int, q{y}, int, q{z});

		auto points = new Point [n];
		foreach (int i, ref point; points)
		{
			readf (" %s %s", &point.x, &point.y);
			point.z = i;
		}

		alias Edge = Tuple !(int, q{u}, int, q{v}, int, q{w});
		Edge [] edges;

		points.schwartzSort !(point => point.x);
		foreach (i; 1..n)
		{
			edges ~= Edge (points[i - 1].z, points[i - 0].z,
			    points[i - 0].x - points[i - 1].x);
		}

		points.schwartzSort !(point => point.y);
		foreach (i; 1..n)
		{
			edges ~= Edge (points[i - 1].z, points[i - 0].z,
			    points[i - 0].y - points[i - 1].y);
		}

		auto p = n.iota.array;

		int root (int v)
		{
			if (p[v] != v)
			{
				p[v] = root (p[v]);
			}
			return p[v];
		}

		bool unite (int u, int v)
		{
			u = root (u);
			v = root (v);
			if (u == v)
			{
				return false;
			}
			p[u] = v;
			return true;
		}

		edges.schwartzSort !(edge => edge.w);
		int res = 0;
		foreach (ref edge; edges)
		{
			if (unite (edge.u, edge.v))
			{
				res += edge.w;
			}
		}
		writeln (res);
	}
}
