#include <bits/stdc++.h>
using namespace std;
const long long N = 1e5 + 5;
long long n, pr[N];
vector<pair<long long, long long> > xx, yy;
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 i) { return (pr[i] == i) ? i : (pr[i] = find(pr[i])); }
signed main() {
  ios_base::sync_with_stdio(false);
  cin >> n;
  for (long long i = 1; i <= n; ++i) {
    long long x, y;
    cin >> x >> y;
    xx.push_back(make_pair(x, i));
    yy.push_back(make_pair(y, i));
  }
  sort(xx.begin(), xx.end());
  sort(yy.begin(), yy.end());
  for (long long i = 1; i <= xx.size() - 1; ++i) {
    pq.push(make_pair(xx[i].first - xx[i - 1].first,
                      make_pair(xx[i].second, xx[i - 1].second)));
  }
  for (long long i = 1; i <= yy.size() - 1; ++i)
    pq.push(make_pair(yy[i].first - yy[i - 1].first,
                      make_pair(yy[i].second, yy[i - 1].second)));
  long long ans = 0;
  for (long long i = 1; i <= n; ++i) pr[i] = i;
  while (!pq.empty()) {
    long long u = pq.top().second.first, v = pq.top().second.second,
              uv = pq.top().first;
    pq.pop();
    if (find(u) != find(v)) {
      pr[find(u)] = find(v);
      ans += uv;
    }
  }
  cout << ans;
}
