#include <bits/stdc++.h>
using namespace std;
long long n, res = 0;
vector<pair<long long, long long> > a, b;
vector<pair<long long, pair<long long, long long> > > adj;
vector<long long> pset, setsize;
void init(long long n) {
  pset.assign(n + 1, 0);
  setsize.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;
  return pset[i] = findset(pset[i]);
}
bool issameset(long long i, long long j) { return findset(i) == findset(j); }
void unionset(long long i, long long j) {
  if (issameset(i, j)) return;
  setsize[findset(i)] += setsize[findset(j)];
  setsize[findset(j)] = 0;
  pset[findset(j)] = findset(i);
}
signed main() {
  ios_base::sync_with_stdio(0);
  cin >> n;
  init(n);
  for (long long i = 1; i <= n; i++) {
    long long u, v;
    cin >> u >> v;
    a.push_back(pair<long long, long long>(u, i));
    b.push_back(pair<long long, long long>(v, i));
  }
  sort(a.begin(), a.end());
  sort(b.begin(), b.end());
  for (long long i = 1; i < n; i++) {
    adj.push_back(
        make_pair(a[i].first - a[i - 1].first,
                  pair<long long, long long>(a[i].second, a[i - 1].second)));
    adj.push_back(
        make_pair(b[i].first - b[i - 1].first,
                  pair<long long, long long>(b[i].second, b[i - 1].second)));
  }
  sort(adj.begin(), adj.end());
  for (long long i = 0; i < adj.size(); i++) {
    long long u = adj[i].second.first, v = adj[i].second.second;
    if (issameset(u, v)) continue;
    unionset(u, v);
    res += adj[i].first;
  }
  cout << res << '\n';
  return 0;
}
