#include <bits/stdc++.h>
using namespace std;
const long long MOD = 1e9 + 7;
const long long N = 1e5 + 5;
long long par[N];
long long n, te, ans = 0, use = 0;
long long find(long long x) {
  if (x == par[x]) return x;
  return par[x] = find(par[x]);
}
struct point {
  long long id, X, Y;
} p[N];
bool cmpx(point a, point b) { return a.X < b.X; }
bool cmpy(point a, point b) { return a.Y < b.Y; }
struct edge {
  long long u, v;
  long long w;
} e[N << 1];
bool cmpe(edge a, edge b) { return a.w < b.w; }
signed main() {
  cin >> n;
  for (long long i = 0; i < n; i++) {
    par[i] = i;
    long long x, y;
    cin >> x >> y;
    p[i].id = i;
    p[i].X = x;
    p[i].Y = y;
  }
  sort(p, p + n, cmpx);
  for (long long i = 1; i < n; i++) {
    e[te].w = p[i].X - p[i - 1].X;
    e[te].u = p[i].id;
    e[te].v = p[i - 1].id;
    te++;
  }
  sort(p, p + n, cmpy);
  for (long long i = 1; i < n; i++) {
    e[te].w = p[i].Y - p[i - 1].Y;
    e[te].u = p[i].id;
    e[te].v = p[i - 1].id;
    te++;
  }
  sort(e, e + te, cmpe);
  for (long long i = 0; i < te; i++) {
    long long st = find(e[i].u);
    long long en = find(e[i].v);
    if (st != en) {
      ans += e[i].w;
      par[st] = en;
      use++;
    }
    if (use == n - 1) {
      cout << ans - 1;
      return 0;
    }
  }
  return 0;
}
