#include <bits/stdc++.h>
using namespace std;
const int p = 1e9 + 7;
const int N = 2e5 + 50;
int n, cnt;
long long ans = 0;
int f[N];
struct orz {
  long long x, y, id;
} a[N];
struct stu {
  long long u, v, w;
} c[N * 2];
bool cmp1(orz a, orz b) { return a.x < b.x; }
bool cmp2(orz a, orz b) { return a.y < b.y; }
bool cmp(stu a, stu b) { return a.w < b.w; }
int fund(int x) {
  if (f[x] == x)
    return x;
  else
    return f[x] = fund(f[x]);
}
int main() {
  scanf("%d", &n);
  for (int i = 1; i <= n; i++) {
    scanf("%lld%lld", &a[i].x, &a[i].y);
    a[i].id = i;
  }
  sort(a + 1, a + 1 + n, cmp1);
  for (int i = 1; i < n; i++) {
    cnt++;
    c[cnt].u = a[i].id;
    c[cnt].v = a[i + 1].id;
    c[cnt].w = min(abs(a[i].x - a[i + 1].x), abs(a[i].y - a[i + 1].y));
  }
  sort(a + 1, a + 1 + n, cmp2);
  for (int i = 1; i < n; i++) {
    cnt++;
    c[cnt].u = a[i].id;
    c[cnt].v = a[i + 1].id;
    c[cnt].w = min(abs(a[i].x - a[i + 1].x), abs(a[i].y - a[i + 1].y));
  }
  sort(c + 1, c + 1 + cnt, cmp);
  for (int i = 1; i <= n; i++) f[i] = i;
  int now = 0, sum = 1;
  while (sum < n) {
    now++;
    int x = c[now].u, y = c[now].v;
    if (fund(x) != fund(y)) {
      f[x] = f[y];
      sum++;
      ans += c[now].w;
    }
  }
  printf("%lld\n", ans);
  return 0;
}
