#include<bits/stdc++.h>
using namespace std;
struct node{
	long long id, xx, yy;
};
struct edge{
	long long a, b, v;
};
long long ans = 0, fa[100005], cnt = 0;
node a[100005];
edge e[10000005];
bool cmp(node x, node y){
	return x.xx < y.xx;
}
bool cmp1(node x, node y){
	return x.yy < y.yy;
}
bool cmp2(edge x, edge y){
	return x.v < y.v;
}
int find(int x){
	if(fa[x] == x) return x;
	else{
		fa[x] = find(fa[x]);
		return fa[x];
	}
}
void Union(int x, int y){
	fa[x] = find(y);
}
int main(){
	int n;
	cin >> n;
	for(int i = 1; i <= n; ++i){
		fa[i] = i;
	}
	for(int i = 1; i <= n; ++i){
		a[i].id = i;
		cin >> a[i].xx >> a[i].yy;
	}
	sort(a + 1, a + n + 1, cmp);
	for(int i = 1; i < n; ++i){
		cnt ++;
		e[cnt].a = a[i].id;
		e[cnt].b = a[i + 1].id;
		e[cnt].v = a[i + 1].xx - a[i].xx;
	}
	sort(a + 1, a + n + 1, cmp1);
	for(int i = 1; i < n; ++i){
		cnt ++;
		e[cnt].a = a[i].id;
		e[cnt].b = a[i + 1].id;
		e[cnt].v = a[i + 1].yy - a[i].yy;
	}
	sort(e + 1, e + cnt + 1, cmp2);
	for(int i = 1; i <= cnt; ++i){
		if(find(e[i].a) != find(e[i].b)){
			ans += e[i].v;
			Union(e[i].a, e[i].b);
		}
	}
	cout << ans;
}