#include <bits/stdc++.h>
using namespace std;
typedef struct distance_x {
  long dwTown;
  long long qwCost_X;
  bool operator>(const distance_x& e) const { return qwCost_X > e.qwCost_X; }
} DIST_X;
typedef struct distance_y {
  long dwTown;
  long long qwCost_Y;
  bool operator>(const distance_y& e) const { return qwCost_Y > e.qwCost_Y; }
} DIST_Y;
typedef struct edge {
  long dwTo;
  long long qwCost;
  bool operator>(const edge& e) const { return qwCost > e.qwCost; }
} EDGE;
typedef struct {
  long long qwX;
  long long qwY;
} POS;
vector<POS> vPosList;
priority_queue<DIST_X, vector<DIST_X>, greater<DIST_X>> que_x;
priority_queue<DIST_Y, vector<DIST_Y>, greater<DIST_Y>> que_y;
priority_queue<EDGE, vector<EDGE>, greater<EDGE>> que_edge;
vector<EDGE> vList[(10000)];
long long prim() {
  bool bUsed[(10000)] = {};
  long long qwAns = 0;
  que_edge.push(EDGE{0, 0});
  while (!que_edge.empty()) {
    EDGE nowEdge = que_edge.top();
    que_edge.pop();
    if (bUsed[nowEdge.dwTo]) continue;
    bUsed[nowEdge.dwTo] = true;
    qwAns += nowEdge.qwCost;
    for (auto iter : vList[nowEdge.dwTo]) {
      que_edge.push(iter);
    }
  }
  return qwAns;
}
void makeEdge() {
  long dwPreTown;
  dwPreTown = que_x.top().dwTown;
  que_x.pop();
  while (!que_x.empty()) {
    DIST_X tmpX = que_x.top();
    que_x.pop();
    long long qwCost =
        min(abs(vPosList[dwPreTown].qwX - vPosList[tmpX.dwTown].qwX),
            abs(vPosList[dwPreTown].qwY - vPosList[tmpX.dwTown].qwY));
    vList[tmpX.dwTown].push_back(EDGE{dwPreTown, qwCost});
    vList[dwPreTown].push_back(EDGE{tmpX.dwTown, qwCost});
    dwPreTown = tmpX.dwTown;
  }
  dwPreTown = que_y.top().dwTown;
  que_y.pop();
  while (!que_y.empty()) {
    DIST_Y tmpY = que_y.top();
    que_y.pop();
    long long qwCost =
        min(abs(vPosList[dwPreTown].qwX - vPosList[tmpY.dwTown].qwX),
            abs(vPosList[dwPreTown].qwY - vPosList[tmpY.dwTown].qwY));
    vList[tmpY.dwTown].push_back(EDGE{dwPreTown, qwCost});
    vList[dwPreTown].push_back(EDGE{tmpY.dwTown, qwCost});
    dwPreTown = tmpY.dwTown;
  }
}
void solve_main() {
  long N;
  cin >> N;
  for (int i = 0; i < N; i++) {
    long long qwX, qwY;
    cin >> qwX >> qwY;
    vPosList.push_back(POS{qwX, qwY});
    que_x.push(DIST_X{i, qwX});
    que_y.push(DIST_Y{i, qwY});
  }
  makeEdge();
  cout << prim() << endl;
}
int main() {
  solve_main();
  return 0;
}
