#include <bits/stdc++.h>
using namespace std;
const int maxm = 1e5 + 10;
struct p {
  int x;
  int ind;
} mat1[maxm], mat2[maxm];
bool cmp(p a, p b) { return a.x < b.x; }
struct e {
  int from, to, val;
  e(int _from = 0, int _to = 0, int _val = 0) {
    from = _from;
    to = _to;
    val = _val;
  }
} edge[maxm << 3];
bool cmp2(e a, e b) { return a.val < b.val; }
int pre[maxm];
int fin(int a) { return (a == pre[a]) ? a : (pre[a] = fin(pre[a])); }
int uni(int a, int b, int val) {
  int aa = fin(a);
  int bb = fin(b);
  if (aa == bb) return 0;
  pre[aa] = bb;
  return val;
}
int main() {
  int n;
  scanf("%d", &n);
  for (int i = 1; i <= n; i++) {
    pre[i] = i;
    scanf("%d%d", &mat1[i].x, &mat2[i].x);
    mat1[i].ind = i;
    mat2[i].ind = i;
  }
  sort(mat1 + 1, mat1 + n + 1, cmp);
  sort(mat2 + 1, mat2 + n + 1, cmp);
  int flag = 0;
  for (int i = 2; i < n; i++) {
    edge[flag++] =
        e{mat1[i].ind, mat1[i - 1].ind, abs(mat1[i].x - mat1[i - 1].x)};
    edge[flag++] =
        e{mat1[i].ind, mat1[i + 1].ind, abs(mat1[i].x - mat1[i + 1].x)};
    edge[flag++] =
        e{mat2[i].ind, mat2[i - 1].ind, abs(mat2[i].x - mat2[i - 1].x)};
    edge[flag++] =
        e{mat2[i].ind, mat2[i + 1].ind, abs(mat2[i].x - mat2[i + 1].x)};
  }
  long long ans = 0;
  sort(edge, edge + flag, cmp2);
  for (int i = 0; i < flag; i++) {
    ans += uni(edge[i].from, edge[i].to, edge[i].val);
  }
  printf("%lld\n", ans);
  return 0;
}
