#include <bits/stdc++.h>
using namespace tr1;
using namespace std;
inline bool feq(const double& a, const double& b) {
  return fabs(a - b) < 1e-10;
}
const int MAXN = 100100;
int N;
pair<int, int> pos[MAXN];
bool in[MAXN];
vector<int> edge[MAXN];
unordered_map<int, unordered_set<int>> has;
int dist(int a, int b) {
  return min(abs(pos[a].first - pos[b].first),
             abs(pos[a].second - pos[b].second));
}
int main() {
  while (cin >> N) {
    has.clear();
    memset(in, 0, sizeof(in));
    for (int i = 0; i < N; ++i) {
      int x, y;
      cin >> x >> y;
      if (has[x].count(y)) in[i] = true;
      has[x].insert(y);
    }
    priority_queue<pair<int, int>, vector<pair<int, int>>,
                   greater<pair<int, int>>>
        que;
    in[0] = true;
    for (int i = 0; i < N; ++i)
      if (!in[i]) que.push(pair<int, int>(dist(0, i), i));
    long long res = 0;
    while (!que.empty()) {
      pair<int, int> d_u = que.top();
      que.pop();
      int d = d_u.first;
      int u = d_u.second;
      if (in[u]) continue;
      res += d;
      in[u] = true;
      for (int i = 0; i < N; ++i)
        if (!in[i]) que.push(pair<int, int>(dist(u, i), i));
    }
    cout << res << endl;
  }
  return 0;
}
