#include <bits/stdc++.h>
using namespace std;
int n;
struct Md {
  int v, u, flag;
} M[100005], C[100005];
struct Node {
  int x, y, z;
} dis[1000005];
bool cmp(Md a, Md b) { return a.v < b.v; }
bool cmp0(Md a, Md b) { return a.u < b.u; }
bool cmp1(Node a, Node b) { return a.z < b.z; }
int book[100005];
void init() {
  for (int i = 1; i <= n; i++) book[i] = i;
}
int getx(int x) {
  if (book[x] != x) book[x] = getx(book[x]);
  return book[x];
}
void mergexy(int x, int y) { book[y] = x; }
void change() {
  for (int i = 1; i <= n; i++) {
    C[i].v = M[i].v;
    C[i].u = M[i].u;
    C[i].flag = M[i].flag;
  }
}
int main() {
  scanf("%d", &n);
  for (int i = 1; i <= n; i++) {
    scanf("%d%d", &M[i].v, &M[i].u);
    M[i].flag = i;
  }
  change();
  int flag = 0;
  sort(C + 1, C + n + 1, cmp);
  for (int i = 2; i < n; i++) {
    dis[++flag].x = C[i].flag, dis[flag].y = C[i - 1].flag,
    dis[flag].z = (min(fabs(C[i].v - C[i - 1].v), fabs(C[i].u - C[i - 1].u)));
  }
  change();
  sort(C + 1, C + n + 1, cmp0);
  for (int i = 2; i < n; i++) {
    dis[++flag].x = C[i].flag, dis[flag].y = C[i - 1].flag,
    dis[flag].z = (min(fabs(C[i].v - C[i - 1].v), fabs(C[i].u - C[i - 1].u)));
  }
  sort(dis + 1, dis + flag + 1, cmp1);
  init();
  int number = 0;
  int sum = 0;
  for (int i = 1; i <= flag; i++) {
    int p = getx(dis[i].x), q = getx(dis[i].y);
    if (p != q) {
      mergexy(p, q);
      number++;
      sum += dis[i].z;
    }
    if (number == n) break;
  }
  cout << sum << endl;
  return 0;
}
