#include <bits/stdc++.h>
using namespace std;
const long long N = 1e5 + 5;
long long n, dem, ans;
long long pset[N], s[N];
vector<pair<long long, long long> > vx, vy;
map<pair<long long, long long>, long long> ma;
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;
bool how_sort(pair<long long, long long> a, pair<long long, long long> b) {
  if (a.second != b.second) return a.second < b.second;
  return a.first < b.first;
}
long long unionfind(long long u) {
  return (u == pset[u]) ? u : (pset[u] = unionfind(pset[u]));
}
bool compare(long long u, long long v) {
  return (unionfind(u) == unionfind(v)) ? true : false;
}
void unionset(long long i, long long j) {
  long long x = unionfind(i), y = unionfind(j);
  if (s[x] > s[y]) {
    pset[y] = x;
    s[x] += s[y];
  } else {
    pset[x] = y;
    s[y] += s[x];
  }
}
signed main() {
  ios_base::sync_with_stdio(false);
  cin.tie(0);
  long long cnt = 0;
  cin >> n;
  for (long long i = 1; i <= n; ++i) {
    long long a, b;
    cin >> a >> b;
    if (ma[pair<long long, long long>(a, b)]) continue;
    ma[pair<long long, long long>(a, b)] = ++cnt;
    vx.push_back(pair<long long, long long>(a, b));
    vy.push_back(pair<long long, long long>(a, b));
    pset[i] = i;
    s[i] = 1;
  }
  sort(vx.begin(), vx.end());
  sort(vy.begin(), vy.end(), how_sort);
  long long i = 0, j = 0;
  for (long long i = 1; i < cnt; ++i) {
    long long a = vx[i].first - vx[i - 1].first;
    pq.push(pair<long long, pair<long long, long long> >(
        a, pair<long long, long long>(ma[vx[i]], ma[vx[i - 1]])));
    long long b = vy[i].second - vy[i - 1].second;
    pq.push(pair<long long, pair<long long, long long> >(
        b, pair<long long, long long>(ma[vy[i]], ma[vy[i - 1]])));
  }
  while (!pq.empty()) {
    pair<long long, pair<long long, long long> > x = pq.top();
    long long w = x.first, u = x.second.first, v = x.second.second;
    pq.pop();
    if (!compare(u, v)) {
      unionset(u, v);
      dem++;
      ans += w;
    }
    if (dem == cnt - 1) break;
  }
  cout << ans;
}
