#include <bits/stdc++.h>
using namespace std;
long long n, m, i, j, k, cc[500000], a, b, c, s;
long long min(long long x, long long y) {
  if (x > y)
    return y;
  else
    return x;
}
int abs(int x) {
  if (x < 0)
    return -x;
  else
    return x;
}
struct p {
  long long x, y, z;
  bool operator<(const p& tt) const { return x < tt.x; }
} s1[500000], s2[500000];
struct pp {
  long long x, y, z;
  bool operator<(const pp& tt) const { return z < tt.z; }
} wow[1000000];
long long find(long long x) {
  if (cc[x] == x)
    return x;
  else {
    cc[x] = find(cc[x]);
    return cc[x];
  }
}
int main() {
  scanf("%lld", &n);
  for (int i = 1; i <= n; i++) {
    scanf("%lld %lld", &s1[i].x, &s1[i].y);
    s2[i].x = s1[i].y;
    s2[i].y = s1[i].x;
    s1[i].z = i;
    s2[i].z = i;
  }
  sort(s1, s1 + n + 1);
  sort(s2, s2 + n + 1);
  a = 0;
  for (int i = 1; i < n; i++) {
    a++;
    wow[i].x = s1[i].z;
    wow[i].y = s1[i + 1].z;
    wow[i].z = (s1[i + 1].x - s1[i].x);
  }
  for (int i = 1; i < n; i++) {
    a++;
    wow[a].x = s2[i].z;
    wow[a].y = s2[i + 1].z;
    wow[a].z = (s2[i + 1].x - s2[i].x);
  }
  sort(wow, wow + a + 1);
  for (int i = 1; i <= n; i++) cc[i] = i;
  for (int i = 1; i <= a; i++) {
    if (find(cc[wow[i].x]) != find(cc[wow[i].y])) {
      cc[find(cc[wow[i].x])] = find(cc[wow[i].y]);
      s += wow[i].z;
    }
  }
  printf("%lld\n", s);
  return 0;
}
