#include <bits/stdc++.h>
int par[100000], rank[100000];
void init(int n) {
  int i;
  for (i = 0; i < n; i++) {
    par[i] = 1;
    rank[i] = 0;
  }
}
int root(int x) {
  if (par[x] == x) return x;
  return root(par[x]);
}
void combsort(int a[], int b[], int c[], int n) {
  int i, h = n / 1.3, swaped, tmp;
  if (h == 0) h = 1;
  while (h != 0 || swaped != 0) {
    swaped = 0;
    if (h == 0) h = 1;
    if (h == 10 || h == 9) h = 11;
    for (i = 0; i < n - h; i++) {
      if (a[i] > a[i + h]) {
        tmp = a[i];
        a[i] = a[i + h];
        a[i + h] = tmp;
        if (b != NULL) {
          tmp = b[i];
          b[i] = b[i + h];
          b[i + h] = tmp;
        }
        if (c != NULL) {
          tmp = c[i];
          c[i] = c[i + h];
          c[i + h] = c[i];
        }
        swaped = 1;
      }
    }
    h = h / 1.3;
  }
}
void unite(int x, int y) {
  x = root(x);
  y = root(y);
  if (x != y) {
    int rx = rank[x], ry = rank[y];
    if (rx < ry) {
      par[x] = y;
    } else {
      par[y] = x;
    }
    if (rx == ry) rank[x]++;
  }
}
int same(int x, int y) {
  if (root(x) == root(y)) return 1;
  return 0;
}
int main(void) {
  int n, i, cnt = 0, sum = 0;
  int x[100000], y[100000], n1[100000], n2[100000];
  int from[200000], to[200000], cost[200000] = {0};
  scanf("%d", &n);
  for (i = 0; i < n; i++) {
    scanf("%d%d", &x[i], &y[i]);
    n1[i] = i;
    n2[i] = i;
  }
  combsort(x, n1, NULL, n);
  combsort(y, n2, NULL, n);
  for (i = 1; i < n; i++) {
    from[cnt] = n1[i - 1];
    to[cnt] = n1[i];
    cost[cnt] = x[i] - x[i - 1];
    cnt++;
    from[cnt] = n2[i - 1];
    to[cnt] = n2[i];
    cost[cnt] = y[i] - y[i - 1];
    cnt++;
  }
  combsort(cost, from, to, cnt);
  init(cnt);
  for (i = 0; i < cnt; i++) {
    if (same(from[i], to[i]) == 0) {
      unite(from[i], to[i]);
      sum += cost[i];
    }
  }
  printf("%d\n", n2[0]);
  return 0;
}
