#include<bits/stdc++.h> 
using namespace std;
const int L = 5000005;
struct point{
	int xx, yy, ww;
}poi[1000005];
struct node{int s, y, w;}edge[L];
long long Fa[L], n, m;
void init(){
    for(int i = 0; i <= n; i++){
    	Fa[i] = i;
	}
}
int Find(int x)
{
    if(Fa[x] == x) return x;
    else return Fa[x] = Find(Fa[x]);
}
void unite(int x,int y)
{
    x = Find(x);
    y = Find(y);
    if(x != y)
    	Fa[y] = x;
}
bool same(int x, int y)
{
    return Find(x) == Find(y);
}
bool cmp(node a, node b)
{
    return a.w < b.w;
}
bool cmp1(point x, point y){
	return x.xx < y.xx;
}
bool cmp2(point x, point y){
	return x.yy < y.yy;
}
int main()
{	
    scanf("%d", &n);
    for(int i = 0; i < n; i++){
    	scanf("%d%d", &poi[i].xx, &poi[i].yy);
    	poi[i].ww = i;
	}
    m = 0;
	sort(poi, poi + n, cmp1);
	for(int i = 0; i < n; i++){
		if(i + 1 < n){
			edge[m].s = poi[i].ww;
			edge[m].y = poi[i + 1].ww;
			edge[m].w = fabs(poi[i].xx - poi[i + 1].xx);
			m++;
		}
		if(i - 1 >= 0){
			edge[m].s = poi[i].ww;
			edge[m].y = poi[i - 1].ww;
			edge[m].w = fabs(poi[i].xx - poi[i - 1].xx);
			m++;
		}
	}
	sort(poi, poi + n, cmp2);
	for(int i = 0; i < n; i++)
        {
		if(i + 1 < n)
                {
			edge[m].s = poi[i].ww;
			edge[m].y = poi[i + 1].ww;
			edge[m].w = fabs(poi[i].yy - poi[i + 1].yy);
			m++;
		}
		if(i - 1 >= 0)
                {
			edge[m].s = poi[i].ww;
			edge[m].y = poi[i - 1].ww;
			edge[m].w = fabs(poi[i].yy - poi[i - 1].yy);
			m++;
		}
	}
	init();
    sort(edge, edge + m, cmp);
   long long su = 0, cnt = 0;
    for(int i = 0; i < m; i++)
    {
        if(cnt == n - 1)			break;
        if(!same(edge[i].s, edge[i].y))
        {
            unite(edge[i].s, edge[i].y);
            su += edge[i].w;
            cnt++;
        }
    }
	printf("%d\n", su);
    return 0;
}