function init(N,i)
{
	for(i=1;i<=N;i++)parent[i]=-1;
}
function find(u){return parent[u]<0?u:parent[u]=find(parent[u]);}
function same(a,b){return find(a)==find(b);}
function unite(a,b)
{
	a=find(a);
	b=find(b);
	if(a==b)return 0;
	if(parent[a]>parent[b])
	{
		parent[b]+=parent[a];
		parent[a]=b;
	}
	else
	{
		parent[a]+=parent[b];
		parent[b]=a;
	}
	return 1;
}
function size(a){return -parent[find(a)];}
function sort(id,l,r,tmp,mid,il,ir)#[l,r)
{
	if(r-l==2)
	{
		if(A[id[l+1]]<A[id[l]])
		{
			tmp=id[l];
			id[l]=id[l+1];
			id[l+1]=tmp;
		}
	}
	else if(r-l>2)
	{
		mid=int((l+r)/2);
		il=l;
		ir=r-1;
		while(il<=ir)
		{
			while(A[id[il]]<A[id[mid]])il++;
			while(A[id[mid]]<A[id[ir]])ir--;
			if(il<ir)
			{
				tmp=id[il];
				id[il]=id[ir];
				id[ir]=tmp;
				if(mid==il)mid=ir;
				else if(mid==ir)mid=il;
				il++;
				ir--;
			}
			else if(il==ir)
			{
				il++;
				ir--;
			}
		}
		sort(id,l,il);
		sort(id,il,r);
	}
}
NR==1{N=+$1}
NR>1{
	x[NR-1]=+$1;
	y[NR-1]=+$2;
}
END{
	for(i=1;i<=N;i++)
	{
		id[i]=i;
		A[i]=x[i];
	}
	sort(id,1,N+1);
	for(i=2;i<=N;i++)
	{
		++sz;
		E[sz]=A[U[sz]=id[i]]-A[V[sz]=id[i-1]];
	}
	for(i=1;i<=N;i++)
	{
		id[i]=i;
		A[i]=y[i];
	}
	sort(id,1,N+1);
	for(i=2;i<=N;i++)
	{
		++sz;
		E[sz]=A[U[sz]=id[i]]-A[V[sz]=id[i-1]];
	}
	for(i=1;i<=sz;i++)
	{
		id[i]=i;
		A[i]=E[i];
	}
	sort(id,1,sz+1);
	init(N);
	ans=0;
	for(i=1;i<=sz;i++)
	{
		if(unite(U[id[i]],V[id[i]]))ans+=E[id[i]];
	}
	printf"%.f\n",ans
}