#include <bits/stdc++.h>
using namespace std;
const long long N = 1e5 + 5;
vector<pair<long long, long long> > a, b;
map<pair<long long, long long>, long long> check;
vector<long long> pset, s;
bool cmp(pair<long long, long long> a, pair<long long, long long> b) {
  return a.second < b.second;
}
void init(long long n) {
  pset.assign(n + 1, -1);
  s.assign(n + 1, 1);
  for (long long i = 1; i <= n; i++) {
    pset[i] = i;
  }
}
long long findset(long long i) {
  if (pset[i] == i)
    return i;
  else
    return pset[i] = findset(pset[i]);
}
void unionset(long long i, long long j) {
  long long x = findset(i), y = findset(j);
  if (s[x] > s[y]) {
    pset[y] = x;
    s[x] += s[y];
  } else {
    pset[x] = y;
    s[y] += s[x];
  }
}
signed main() {
  long long n, cnt = 0, ans = 0;
  cin >> n;
  for (long long i = 1; i <= n; i++) {
    long long x, y;
    cin >> x >> y;
    if (check[pair<long long, long long>(x, y)])
      continue;
    else {
      a.push_back(pair<long long, long long>(x, y));
      b.push_back(pair<long long, long long>(x, y));
      check[pair<long long, long long>(x, y)] = ++cnt;
    }
  }
  init(a.size() + 1);
  sort(a.begin(), a.end());
  sort(b.begin(), b.end(), cmp);
  priority_queue<pair<long long, pair<long long, long long> >,
                 vector<pair<long long, pair<long long, long long> > >,
                 greater<pair<long long, pair<long long, long long> > > >
      q;
  for (long long i = 0; i < a.size() - 1; i++) {
    long long x = a[i].first, y = a[i].second;
    q.push(pair<long long, pair<long long, long long> >(
        a[i + 1].first - x,
        pair<long long, long long>(check[a[i]], check[a[i + 1]])));
  }
  for (long long i = 0; i < a.size() - 1; i++) {
    long long x = b[i].first, y = b[i].second;
    q.push(pair<long long, pair<long long, long long> >(
        b[i + 1].second - y,
        pair<long long, long long>(check[b[i]], check[b[i + 1]])));
  }
  while (!q.empty()) {
    long long c = q.top().first, u = q.top().second.first,
              v = q.top().second.second;
    q.pop();
    if (findset(u) != findset(v)) {
      ans += c;
      unionset(u, v);
    }
  }
  cout << ans;
}
