#include <bits/stdc++.h>
using namespace std;
const int N = 100303;
const long long inf = (long long)1 << 40;
int f[N];
struct node {
  int id, val;
} a[N], b[N];
struct edge {
  int x, y, val;
} c[N];
int find(int x) {
  if (f[x] != x) f[x] = find(f[x]);
  return f[x];
}
int cmp(node a, node b) { return a.val < b.val; }
int cmp2(edge a, edge b) { return a.val < b.val; }
int main() {
  int n;
  cin >> n;
  for (int i = 1; i <= n; i++) {
    int x, y;
    cin >> x >> y;
    a[i].id = i;
    a[i].val = x;
    b[i].id = i;
    b[i].val = y;
  }
  sort(a + 1, a + n + 1, cmp);
  sort(b + 1, b + n + 1, cmp);
  for (int i = 1; i <= n; i++) f[i] = i;
  long long ans = 0;
  int t = 0;
  for (int i = 2; i <= n; i++) {
    t++;
    c[t].x = a[i - 1].id;
    c[t].y = a[i].id;
    c[t].val = abs(a[i].val - a[i - 1].val);
  }
  for (int i = 2; i <= n; i++) {
    t++;
    c[t].x = b[i - 1].id;
    c[t].y = b[i].id;
    c[t].val = abs(b[i].val - b[i - 1].val);
  }
  sort(c + 1, c + t + 1, cmp2);
  for (int i = 1; i <= t; i++) {
    int x = find(c[i].x);
    int y = find(c[i].y);
    if (x != y) {
      ans += c[i].val;
      f[x] = y;
    }
  }
  cout << ans << endl;
  return 0;
}
