#include <bits/stdc++.h>
using namespace std;
long long n, cnt = 0, res = 0, x, y, farm[300000];
vector<pair<long long, long long> > adjx, adjy;
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> > > >
    pq;
long long Find(long long n) {
  if (farm[n] < 0)
    return n;
  else
    return farm[n] = Find(farm[n]);
}
void Union(long long x, long long y) {
  x = Find(x), y = Find(y);
  if (x != y) {
    farm[x] += farm[y];
    farm[y] = x;
  }
}
signed main() {
  cin >> n;
  for (long long i = 1; i <= n; i++) {
    cin >> x >> y;
    adjx.push_back({x, i});
    adjy.push_back({y, i});
  }
  sort(adjx.begin(), adjx.end());
  sort(adjy.begin(), adjy.end());
  for (long long i = 0; i <= n - 2; i++) {
    pq.push({abs(adjx[i].first - adjx[i + 1].first),
             {adjx[i].second, adjx[i + 1].second}});
    pq.push({abs(adjy[i].first - adjy[i + 1].first),
             {adjy[i].second, adjy[i + 1].second}});
  }
  memset(farm, -1, sizeof(farm));
  while (!pq.empty()) {
    if (cnt == n - 1) break;
    long long u = pq.top().second.first, v = pq.top().second.second,
              val = pq.top().first;
    pq.pop();
    if (Find(u) != Find(v)) {
      cnt++;
      Union(u, v);
      res = res + val;
    }
  }
  cout << res;
}
