#include <bits/stdc++.h>
using namespace std;
int dx[] = {0, 1, 0, -1}, dy[] = {1, 0, -1, 0};
pair<int, int> x[100010], y[100010];
map<pair<int, int>, int> mp;
long long mincost[100010];
bool used[100010];
signed main(void) {
  int n;
  cin >> n;
  for (long long i = (long long)0; i < (long long)n; ++i) {
    int a, b;
    cin >> a >> b;
    x[i] = {a, i};
    y[i] = {b, i};
  }
  sort(x, x + n);
  sort(y, y + n);
  for (long long i = (long long)1; i < (long long)n; ++i) {
    mp[make_pair(x[i].second, x[i - 1].second)] =
        abs(x[i].first - x[i - 1].first);
    mp[make_pair(x[i - 1].second, x[i].second)] =
        abs(x[i].first - x[i - 1].first);
  }
  for (long long i = (long long)1; i < (long long)n; ++i) {
    if (mp.find(make_pair(y[i].second, y[i - 1].second)) != mp.end()) {
      mp[make_pair(y[i].second, y[i - 1].second)] =
          min(mp[make_pair(y[i].second, y[i - 1].second)],
              abs(y[i].first - y[i - 1].first));
      mp[make_pair(y[i - 1].second, y[i].second)] =
          min(mp[make_pair(y[i - 1].second, y[i].second)],
              abs(y[i].first - y[i - 1].first));
    } else {
      mp[make_pair(y[i].second, y[i - 1].second)] =
          abs(y[i].first - y[i - 1].first);
      mp[make_pair(y[i - 1].second, y[i].second)] =
          abs(y[i].first - y[i - 1].first);
    }
  }
  for (long long i = (long long)0; i < (long long)n; ++i)
    mincost[i] = (1LL << 60), used[i] = false;
  mincost[0] = 0;
  int res = 0;
  while (true) {
    int v = -1;
    for (long long u = (long long)0; u < (long long)n; ++u) {
      if (!used[u] && (v == -1 || mincost[u] < mincost[v])) v = u;
    }
    if (v == -1) break;
    used[v] = true;
    res += mincost[v];
    for (long long u = (long long)0; u < (long long)n; ++u) {
      int tmpu = u, tmpv = v;
      if (mp.find(make_pair(v, u)) != mp.end())
        mincost[u] = min(mincost[u], (long long)mp[make_pair(v, u)]);
    }
  }
  cout << res << endl;
  return 0;
}
