/*
	D.built?
	by sbn
*/
#include<iostream>
#include<cstdio>
#include<cstdlib>
#include<cstring>
#include<algorithm>
#include<queue>
#include<set>
#include<map>
#include<vector>
#include<cmath>
using namespace std;
typedef long long ll;
#define For(a,b,c) for (int (a)=(b);(a)<(c);(a)++)
#define mp make_pair
pair<pair<ll,ll>,int> rex[505001],rey[505001];
struct node{
	int x,y;
	ll len;
	bool operator<(const node &x){
		return len<x.len;
	}
} edg[5000001];
int n,len;
int fa[550001];
ll a,b;
ll link(ll x1,ll y1,ll x2,ll y2){
	return min(abs(x1-x2),abs(y1-y2));	
}
ll find_father(int u){
	if (fa[u]!=u)	fa[u]=find_father(fa[u]);
	return fa[u];
}
ll kruskal(){
    sort(edg,edg+len);
    For(i,0,n)	fa[i]=i;
    int ans=0,cnt=0;
    For(i,0,len){
        int u=edg[i].x, v=edg[i].y;
		ll w=edg[i].len;
        int fu=find_father(u), fv=find_father(v);
        if(fu==fv) continue;
        ans+=w;
        fa[fv]=fu; cnt++;
        if(cnt==n-1) break;
    }
    return ans;
}
int main(){
	cin>>n;
	For(i,0,n)	{
		cin>>a>>b;
		rex[i]=mp(mp(a,b),i);
		rey[i]=mp(mp(b,a),i);
	}
	sort(rex,rex+n);
	For(i,0,n-1){
		edg[len].x=rex[i].second;
		edg[len].y=rex[i+1].second;
		edg[len].len=link(rex[i].first.first,rex[i].first.second,rex[i+1].first.first,rex[i+1].first.second);
		len++;
	}
	sort(rey,rey+n);
	For(i,0,n-1){
		edg[len].x=rey[i].second;
		edg[len].y=rey[i+1].second;
		edg[len].len=link(rey[i].first.first,rey[i].first.second,rey[i+1].first.first,rey[i+1].first.second);
		len++;
	}
	cout<<kruskal()<<endl;
	return 0;
}