#include <bits/stdc++.h>
using namespace std;
long long ans = 0, n, f[100001], sz[100001];
vector<pair<long long, pair<long long, long long> > > edge;
struct point {
  long long x, y, og;
} p[100001];
bool cmp(point &a, point &b) { return a.x < b.x; }
bool cmp2(point &a, point &b) { return a.y < b.y; }
long long getf(long long u) {
  if (u == f[u])
    return u;
  else
    return getf(f[u]);
}
void joint(long long u, long long v) {
  if (sz[u] > sz[v]) {
    f[v] = u;
    sz[u] += sz[v];
  } else {
    f[u] = v;
    sz[v] += sz[u];
  }
}
signed main() {
  ios_base::sync_with_stdio(false);
  cin.tie(0);
  cout.tie(0);
  cin >> n;
  for (long long i = 0; i < n; i++) {
    cin >> p[i].x >> p[i].y;
    p[i].og = i;
    f[i] = i;
  }
  sort(p, p + n, cmp);
  for (long long i = 0; i < n - 1; i++)
    edge.push_back(pair<long long, pair<long long, long long> >(
        min(p[i + 1].x - p[i].x, abs(p[i + 1].y - p[i].y)),
        pair<long long, long long>(p[i].og, p[i + 1].og)));
  sort(p, p + n, cmp2);
  for (long long i = 0; i < n - 1; i++)
    edge.push_back(pair<long long, pair<long long, long long> >(
        min(p[i + 1].y - p[i].y, abs(p[i + 1].x - p[i].x)),
        pair<long long, long long>(p[i].og, p[i + 1].og)));
  sort(edge.begin(), edge.end());
  for (long long i = 0; i < edge.size(); i++) {
    pair<long long, pair<long long, long long> > temp = edge[i];
    long long cost = temp.first, u = temp.second.first, v = temp.second.second;
    long long pu = getf(u), pv = getf(v);
    if (pu != pv) {
      ans += cost;
      joint(pu, pv);
    }
  }
  cout << ans;
}
