#include <bits/stdc++.h>
typedef struct tyouten {
  long long id, x, y;
} V;
int xsort(const void* a, const void* b) {
  long long p = (*(V*)a).x, q = (*(V*)b).x;
  return p < q ? -1 : p > q ? 1 : 0;
}
int ysort(const void* a, const void* b) {
  long long p = (*(V*)a).y, q = (*(V*)b).y;
  return p < q ? -1 : p > q ? 1 : 0;
}
typedef struct edge {
  long long s, g, c;
} E;
typedef struct graph {
  long long vcnt, ecnt;
  E e[200010];
  long long id[100010];
} G;
int csort(const void* a, const void* b) {
  long long p = (*(E*)a).c, q = (*(E*)b).c;
  return p < q ? -1 : p > q ? 1 : 0;
}
V v[100010];
G g;
void readgraph() {
  long long n;
  scanf("%lld", &n);
  for (long long i = (0); i < (n); i++) {
    long long x, y;
    scanf("%lld%lld", &x, &y);
    v[i].id = i;
    v[i].x = x;
    v[i].y = y;
  }
  qsort(v, n, sizeof(V), xsort);
  for (long long i = (0); i < (n - 1); i++) {
    g.e[i].s = v[i].id;
    g.e[i].g = v[i + 1].id;
    g.e[i].c = v[i + 1].x - v[i].x;
  }
  qsort(v, n, sizeof(V), ysort);
  for (long long i = (0); i < (n - 1); i++) {
    g.e[n - 1 + i].s = v[i].id;
    g.e[n - 1 + i].g = v[i + 1].id;
    g.e[n - 1 + i].c = v[i + 1].y - v[i].y;
  }
  g.vcnt = n;
  g.ecnt = (n - 1) * 2;
  qsort(g.e, g.ecnt, sizeof(E), csort);
}
int uniroot[100010], unicnt[100010];
void ufinit(int n) {
  for (int i = 0; i < n; i++) {
    uniroot[i] = i;
    unicnt[i] = 1;
  }
}
int root(int x) { return uniroot[x] != x ? uniroot[x] = root(uniroot[x]) : x; }
int same(int x, int y) { return root(x) == root(y); }
void uni(int x, int y) {
  if ((x = root(x)) == (y = root(y))) return;
  uniroot[x] = y;
  unicnt[y] += unicnt[x];
}
long long saishou[100010];
void kurasukaru(G g) {
  ufinit(g.vcnt);
  for (long long i = (0); i < (g.ecnt); i++) {
    if (!same(g.e[i].s, g.e[i].g)) {
      uni(g.e[i].s, g.e[i].g);
      saishou[i] = 1;
    }
  }
}
int main() {
  readgraph();
  kurasukaru(g);
  long long ans = 0;
  for (long long i = (0); i < (g.ecnt); i++)
    if (saishou[i]) ans += g.e[i].c;
  printf("%lld\n", ans);
  return 0;
}
