#include <bits/stdc++.h>
using namespace std;
const int kn = 2e5 + 5;
const long long mod = 1e9 + 7;
long long n, par[kn];
long long ans = 0;
struct data {
  int first, second;
  int id;
};
bool option(data cac, data lon) {
  if (cac.first != lon.first) return cac.first < lon.first;
  return cac.second < lon.second;
}
data a[2][kn];
int Find(int i) {
  if (par[i] == i) return i;
  return par[i] = Find(par[i]);
}
void dj(int i, int j, int cost) {
  int pi = Find(i), pj = Find(j);
  if (pi == pj) return;
  par[pi] = pj;
  ans += cost;
}
int la[2][kn], ra[2][kn];
set<pair<long long, pair<long long, long long> > > pq;
int main() {
  cin >> n;
  for (int i = 1; i <= n; i++) par[i] = i;
  for (int i = 1; i <= n; i++) {
    cin >> a[0][i].first >> a[0][i].second;
    a[1][i].first = a[0][i].second;
    a[1][i].second = a[0][i].first;
    a[0][i].id = a[1][i].id = i;
    la[0][i] = la[1][i] = i - 1;
    ra[0][i] = ra[1][i] = i + 1;
  }
  la[0][1] = la[1][1] = -1;
  ra[0][n] = ra[1][n] = -1;
  sort(a[0] + 1, a[0] + n + 1, option);
  sort(a[1] + 1, a[1] + n + 1, option);
  for (int i = 2; i <= n; i++) {
    pq.insert(pair<long long, pair<long long, long long> >(
        a[0][i].first - a[0][i - 1].first, pair<long long, long long>(i, 0)));
    pq.insert(pair<long long, pair<long long, long long> >(
        a[1][i].first - a[1][i - 1].first, pair<long long, long long>(i, 1)));
  }
  while (pq.size()) {
    pair<long long, pair<long long, long long> > tmp = *pq.begin();
    pq.erase(pq.begin());
    dj(a[tmp.second.second][tmp.second.first].id,
       a[tmp.second.second][tmp.second.first - 1].id,
       a[tmp.second.second][tmp.second.first].first -
           a[tmp.second.second][tmp.second.first - 1].first);
  }
  cout << ans;
}
