#include <bits/stdc++.h>

using namespace std;
typedef long long ll;
const int N=1e5+10;
int pre[N];

struct Node{
    int x,y,ind;
}v1[N],v[4*N];

int cmp1(Node a,Node b)
{
    if(a.x==b.x)
        return a.y<b.y;
    return a.x<b.x;
}
int cmp2(Node a,Node b)
{
    if(a.y==b.y)
        return a.x<b.x;
    return a.y<b.y;
}
int cmp(Node a,Node b)
{
    return a.ind<b.ind;
}
int find(int x){    return pre[x]==x?x:find(pre[x]);}
int vind=0;
int main()
{
    int n,x,y;
    vind=0;
    scanf("%d",&n);
    for(int i=0;i<n;i++)
    {
        pre[i]=i;
        scanf("%d%d",&v1[i].x,&v1[i].y);
        v1[i].ind=i;
    }
    sort(v1,v1+v1ind,cmp1);
    for(int i=0;i<n-1;i++)
    {
        v[vind].x=v1[i].ind;v[vind].y=v1[i+1].ind;v[vind++].ind=min(abs(v1[i].x-v1[i+1].x),abs(v1[i].y-v1[i+1].y));
    }
    sort(v1,v1+v1ind,cmp2);
    for(int i=0;i<v1ind-1;i++)
    {
        v[vind].x=v1[i].ind;v[vind].y=v1[i+1].ind;v[vind++].ind=min(abs(v1[i].x-v1[i+1].x),abs(v1[i].y-v1[i+1].y));
    }
    sort(v,v+vind,cmp);
    int m=n-1,i=0;
    ll ans=0;
    while(i<vind)
    {
        if(m==0)    break;
        int prex=find(v[i].x),prey=find(v[i].y);
        if(prex!=prey)
        {
            pre[prex]=prey;
            m--;
            ans+=(ll)v[i].ind;
        }
        i++;
    }
    printf("%lld\n",ans);
    return 0;
}
