#include <iostream>
#include<cstdio>
#include<algorithm>
#include<cmath>
typedef long long ll;
using namespace std;
int fa[200005];
struct Node{
  ll x,y;
  int id;
}a[100005];
struct Edge{
  int p1,p2;
  ll cost;
}edge[200005];
bool cmp1(Node a,Node b)
{ 
     return a.x<b.x;
 }
bool cmp2(Node a,Node b)
{ 
     return a.y<b.y; 
}
bool cmp3(Edge a,Edge b){ return a.cost<b.cost; }
int findd(int a){
  if(fa[a]==a) return fa[a];
  else return fa[a]=findd(fa[a]);
}
int main()
{
    int n;
    scanf("%d",&n);
    for(int i=1;i<=n;i++) {scanf("%lld%lld",&a[i].x,&a[i].y); a[i].id=i; fa[i]=i;}
    sort(a+1,a+1+n,cmp1);
    int cnt=0;
    for(int i=2;i<=n;i++){
        edge[++cnt].p1=a[i-1].id;
        edge[cnt].p2=a[i].id;
        edge[cnt].cost=a[i].x-a[i-1].x;
    }
    sort(a+1,a+1+n,cmp2);
    for(int i=2;i<=n;i++){
        edge[++cnt].p1=a[i-1].id;
        edge[cnt].p2=a[i].id;
        edge[cnt].cost=a[i].y-a[i-1].y;
    }
    sort(edge+1,edge+1+cnt,cmp3);
    ll ans=0;int num=0;
    for(int i=1;i<=cnt;i++){
        int fa_p1=findd(edge[i].p1);
        int fa_p2=findd(edge[i].p2);
        if(fa_p1==fa_p2) continue;
        else{
            fa[fa_p1]=fa_p2;
            num++;
            ans+=(edge[i].cost);
        }
        if(num==n-1) break;
    }
    printf("%lld\n",ans);
    return 0;
}