#include<bits/stdc++.h>

#define FOR(i, a, b) for(int(i)=(a);(i)<(b);(i)++)
#define REP(i, n) FOR((i), 0, (n))

#define RFOR(i, b, a) for(int(i)=(b); (i)>=(a); (i)--)
#define RREP(i, n) FOR((i), (n), 0)

#define pb push_back
#define mp make_pair 

using namespace std;

const int INF=INT_MAX/4;
const int MOD=1000000007;
const double EPS=1e-14;

const bool debug_flag=true;

void debug(string str){
	if(debug_flag){
		cout<<str<<endl;
	}
}

void debugs(string str){
	if(debug_flag){
		cout<<str;
	}
}

class Edge{
public:
  int from, to, cost;
  bool used;
  
  bool operator<(const Edge &b) const{
    if(cost < b.cost){
      return true;
    }else{
      return false;
    }
  }
};

int M=100000;
vector < vector < Edge > > edge;
int n;

void prim(){
  int start, index_i, index_j, add;
  vector < int > s;
  Edge min_cost;
  bool used[M]={0};
  
  for(int i=0; i<n; i++){
    sort(edge[i].begin(), edge[i].end());
  }

  start=0;
  s.push_back(start);
  used[start]=true;
  for(int i=0; i<n-1; i++){
    min_cost.cost=1<<31;
    min_cost.cost--;
    int sl=s.size();
    for(int j=0; j<sl; j++){
    	int l=edge[s[j]].size();
      for(int k=0; k<l; k++){
	if(used[edge[s[j]][k].to]==false && edge[s[j]][k].cost < min_cost.cost){
	  min_cost=edge[s[j]][k];
	  add=edge[s[j]][k].to;
	  index_i=s[j];
	  index_j=k;
	}
      }
    }
    edge[index_i][index_j].used=true;
    //edge[index_j][index_i].used=true;
    s.push_back(add);
    used[add]=true;
  }
  
}

class Point{
public:
  int id, x, y;
};

bool comp_x(Point a, Point b){
    return a.x < b.x;
}

bool comp_y(Point a, Point b){
    return a.y < b.y;
}

int main(int argc, char* argv[]){
	cin.tie(0);
	ios::sync_with_stdio(0);
	cout.precision(10);

	int x, y;

	cin>>n;
	vector<Point> p(n);

	edge.resize(n);
	for(int i=0; i<n; i++){
		cin>>p[i].x>>p[i].y;
		p[i].id=i;
	}


	int cost;
	sort(p.begin(), p.end(), comp_x);
	for(int i=0; i<n-1; i++){
		int j=i+1;
		while(j<n && p[i+1].x-p[i].x == p[j].x-p[i].x){
			cost=min(abs(p[i].x-p[i+1].x), abs(p[i].y-p[i+1].y));
			edge[p[i].id].push_back((Edge){p[i].id, p[i+1].id, cost, false});
			edge[p[i+1].id].push_back((Edge){p[i+1].id, p[i].id, cost, false});
			j++;
		}
	}
	sort(p.begin(), p.end(), comp_y);
	for(int i=0; i<n-1; i++){
		int j=i+1;
		while(j<n && p[i+1].y-p[i].y == p[j].y-p[i].y){
			cost=min(abs(p[i].x-p[i+1].x), abs(p[i].y-p[i+1].y));
			edge[p[i].id].push_back((Edge){p[i].id, p[i+1].id, cost, false});
			edge[p[i+1].id].push_back((Edge){p[i+1].id, p[i].id, cost, false});
			j++;
		}
	}

	prim();

	int c=0;
	for(int i=0; i<edge.size(); i++){
		int l=edge[i].size();
		for(int j=0; j<l; j++){
			if(edge[i][j].used){
				c+=edge[i][j].cost;
			}
		}
	}

	cout<<c<<endl;

	return 0;
}

