#include <bits/stdc++.h>
using namespace std;
const int iinf = 1e9 + 7;
const int oo = 0x3f3f3f3f;
const long long linf = 1ll << 60;
const double dinf = 1e60;
template <typename T>
inline void scf(T &x) {
  bool f = 0;
  x = 0;
  char c = getchar();
  while ((c < '0' || c > '9') && c != '-') c = getchar();
  if (c == '-') {
    f = 1;
    c = getchar();
  }
  while (c >= '0' && c <= '9') {
    x = x * 10 + c - '0';
    c = getchar();
  }
  if (f) x = -x;
  return;
}
template <typename T1, typename T2>
void scf(T1 &x, T2 &y) {
  scf(x);
  return scf(y);
}
template <typename T1, typename T2, typename T3>
void scf(T1 &x, T2 &y, T3 &z) {
  scf(x);
  scf(y);
  return scf(z);
}
template <typename T1, typename T2, typename T3, typename T4>
void scf(T1 &x, T2 &y, T3 &z, T4 &w) {
  scf(x);
  scf(y);
  scf(z);
  return scf(w);
}
inline char mygetchar() {
  char c = getchar();
  while (c == ' ' || c == '\n') c = getchar();
  return c;
}
template <typename T>
inline bool chkmax(T &x, const T &y) {
  return y > x ? x = y, 1 : 0;
}
template <typename T>
inline bool chkmin(T &x, const T &y) {
  return y < x ? x = y, 1 : 0;
}
const int maxn = 2e5 + 100;
int n;
int a[maxn], b[maxn], id[maxn], par[maxn];
pair<int, int> pnt[maxn], pnt2[maxn];
inline int F(int u) { return par[u] == u ? u : par[u] = F(par[u]); }
struct item {
  int typ, x, cur, d;
  item() {}
  item(int typ, int x, int cur, int d) : typ(typ), x(x), cur(cur), d(d) {}
  bool operator<(const item &a) const { return d > a.d; }
};
priority_queue<item> heap;
int main() {
  scf(n);
  for (int i = 0, _end_ = (n); i < _end_; ++i)
    scf(pnt[i].first, pnt[i].second), par[i] = i;
  sort(pnt, pnt + n);
  for (int i = 0, _end_ = (n); i < _end_; ++i)
    pnt2[i] = make_pair(pnt[i].second, i);
  sort(pnt2, pnt2 + n);
  for (int i = 0, _end_ = (n); i < _end_; ++i) {
    id[pnt2[i].second] = i;
    b[i] = pnt2[i].first;
    a[i] = pnt[i].first;
  }
  a[n] = b[n] = iinf;
  for (int i = 0, _end_ = (n); i < _end_; ++i) {
    item foo = item(0, i, i + 1, a[i + 1] - a[i]);
    heap.push(foo);
    foo = item(1, i, i + 1, b[i + 1] - b[i]);
    heap.push(foo);
  }
  int tot = n;
  long long ans = 0;
  while (tot > 1) {
    for (;;) {
      item foo = heap.top();
      heap.pop();
      int x, y;
      long long bar = foo.d;
      if (foo.typ)
        x = id[foo.x], y = id[foo.cur];
      else
        x = foo.x, y = foo.cur;
      x = F(x), y = F(y);
      ++foo.cur;
      if (foo.typ)
        foo.d = b[foo.cur] - b[foo.x];
      else
        foo.d = a[foo.cur] - a[foo.x];
      heap.push(foo);
      if (x == y) continue;
      par[x] = y;
      ans += bar;
      break;
    }
    --tot;
  }
  printf("%lld\n", ans);
  return 0;
}
