#include <bits/stdc++.h>
using namespace std;
const int N = 1e5 + 10;
int pre[N];
struct Node {
  int x, y, ind;
} v1[N], v[4 * N];
int cmp1(Node a, Node b) {
  if (a.x == b.x) return a.y < b.y;
  return a.x < b.x;
}
int cmp2(Node a, Node b) {
  if (a.y == b.y) return a.x < b.x;
  return a.y < b.y;
}
int cmp(Node a, Node b) { return a.ind < b.ind; }
int find(int x) { return pre[x] == x ? x : find(pre[x]); }
int v1ind = 0, v2ind = 0, vind = 0;
int main() {
  int n, x, y;
  scanf("%d", &n);
  for (int i = 1; i <= n; i++) {
    pre[i] = i;
    scanf("%d%d", &x, &y);
    v1[v1ind].x = x;
    v1[v1ind].y = y;
    v1[v1ind++].ind = i;
  }
  sort(v1, v1 + v1ind, cmp1);
  for (int i = 0; i < v1ind - 1; i++) {
    v[vind].x = v1[i].ind;
    v[vind].y = v1[i + 1].ind;
    v[vind++].ind = min(abs(v1[i].x - v1[i + 1].x), abs(v1[i].y - v1[i + 1].y));
  }
  sort(v1, v1 + v1ind, cmp2);
  for (int i = 0; i < v1ind - 1; i++) {
    v[vind].x = v1[i].ind;
    v[vind].y = v1[i + 1].ind;
    v[vind++].ind = min(abs(v1[i].x - v1[i + 1].x), abs(v1[i].y - v1[i + 1].y));
  }
  sort(v, v + vind, cmp);
  int m = n - 1, i = 0;
  long long ans = 0;
  while (i < vind) {
    if (m == 0) break;
    int prex = find(v[i].x), prey = find(v[i].y);
    if (prex != prey) {
      pre[prex] = prey;
      m--;
      ans += (long long)v[i].ind;
    }
    i++;
  }
  printf("%lld\n", ans);
  return 0;
}
