#include <bits/stdc++.h>
using namespace std;
typedef struct {
  long long x, y, id;
} ii;
long long dist(ii a, ii b) { return min(abs(a.x - b.x), abs(a.y - b.y)); }
vector<long long> up;
long long fp(long long u) {
  if (up[u] < 0)
    return u;
  else
    return up[u] = fp(up[u]);
}
void unite(long long u, long long v) {
  long long x = fp(u);
  long long y = fp(v);
  if (x != y) up[x] = y;
}
signed main() {
  long long n;
  cin >> n;
  up.resize(n, -1);
  vector<ii> p(n);
  long long i = 0;
  for (auto &v : p) {
    v.id = i++;
    cin >> v.x >> v.y;
  }
  auto cmp = [](tuple<long long, ii, ii> a, tuple<long long, ii, ii> b) {
    return get<0>(a) > get<0>(b);
  };
  priority_queue<tuple<long long, ii, ii>, vector<tuple<long long, ii, ii> >,
                 decltype(cmp)>
      pq(cmp);
  sort(p.begin(), p.end(), [](ii lhs, ii rhs) { return lhs.x < rhs.x; });
  for (auto it = p.begin(); it != prev(p.end()); it++) {
    long long d = dist(*it, *next(it));
    pq.push({d, *it, *next(it)});
  }
  sort(p.begin(), p.end(), [](ii lhs, ii rhs) { return lhs.y < rhs.y; });
  for (auto it = p.begin(); it != prev(p.end()); it++) {
    long long d = dist(*it, *next(it));
    pq.push({d, *it, *next(it)});
  }
  long long cnt = n;
  long long res = 0;
  while (!pq.empty()) {
    long long d;
    ii a, b;
    tie(d, a, b) = pq.top();
    pq.pop();
    if (fp(a.id) != fp(b.id)) {
      n--;
      res += d;
      unite(fp(a.id), fp(b.id));
    }
  }
  cout << res << endl;
}
