#include <bits/stdc++.h>
using namespace std;
struct part {
  long long v;
  int id;
};
struct part1 {
  int x, y;
  long long v;
};
bool cmp(struct part a, struct part b) { return (a.v < b.v); }
int f[100010];
int find1(int x) {
  if (f[x] == x)
    return (x);
  else
    return (find1(f[x]));
}
bool cmp1(struct part1 a, struct part1 b) { return (a.v < b.v); }
struct part x[100010], y[100010];
struct part1 a[200010];
int n;
int main() {
  scanf("%d", &n);
  for (int i = 1; i <= n; i++) {
    long long xx, yy;
    scanf("%lld%lld", &xx, &yy);
    x[i].v = xx;
    x[i].id = i;
    y[i].v = yy;
    y[i].id = i;
  }
  sort(x + 1, x + 1 + n, cmp);
  sort(y + 1, y + 1 + n, cmp);
  int o = 0;
  for (int i = 1; i <= n - 1; i++) {
    o++;
    a[o].x = x[i].id;
    a[o].y = x[i + 1].id;
    a[o].v = x[i + 1].v - x[i].v;
  }
  for (int i = 1; i <= n - 1; i++) {
    o++;
    a[o].x = y[i].id;
    a[o].y = y[i + 1].id;
    a[o].v = y[i + 1].v - y[i].v;
  }
  sort(a + 1, a + 1 + o, cmp1);
  for (int i = 1; i <= n; i++) f[i] = i;
  int k = 0;
  long long ans = 0;
  for (int i = 1; i <= o; i++) {
    int fa = find1(a[i].x);
    int fb = find1(a[i].y);
    if (fa != fb) {
      f[fa] = fb;
      ans += a[i].v;
      k++;
    }
    if (k == n - 1) break;
  }
  printf("%lld\n", ans);
  return (0);
}
