#include <bits/stdc++.h>
using namespace std;
template <typename T>
void out(T x) {
  cout << x << endl;
  exit(0);
}
const long long mod = 1e9 + 7;
const int maxn = 1e6 + 5;
int n;
long long x[maxn], y[maxn];
struct DSU {
  int n;
  vector<int> siz, par;
  int init_calls;
  DSU() { init_calls = 0; }
  void init(int n) {
    assert(++init_calls == 1);
    this->n = n;
    siz.resize(n + 10, 1);
    par.resize(n + 10);
    for (int i = 1; i <= n; i++) par[i] = i;
  }
  int parent(int x) {
    assert(init_calls == 1);
    assert(x >= 1 && x <= n);
    if (x == par[x]) return x;
    return par[x] = parent(par[x]);
  }
  bool join(int x, int y) {
    assert(init_calls == 1);
    x = parent(x);
    y = parent(y);
    if (x == y) return false;
    if (siz[x] < siz[y]) swap(x, y);
    par[y] = x;
    siz[x] += siz[y];
    return true;
  }
  void clear() {
    init_calls = 0;
    n = 0;
    siz.clear();
    par.clear();
  }
};
long long dist(pair<int, int> p) {
  int i = p.first;
  int j = p.second;
  return min(abs(x[i] - x[j]), abs(y[i] - y[j]));
}
struct cmp {
  bool operator()(pair<int, int> X, pair<int, int> Y) {
    return dist(X) < dist(Y);
  }
};
int main() {
  ios_base::sync_with_stdio(false);
  cin.tie(0);
  cout.tie(0);
  cin >> n;
  set<int> alive;
  for (int i = 1; i <= n; i++) {
    cin >> x[i] >> y[i];
    alive.insert(i);
  }
  DSU dsu;
  dsu.init(n);
  set<pair<int, int>, cmp> s;
  auto add = [&](int x) {
    for (int i : alive) s.insert({x, i});
    alive.erase(x);
  };
  add(1);
  long long res = 0;
  while (s.size()) {
    auto cur = *s.begin();
    int a = cur.first;
    int b = cur.second;
    s.erase(s.begin());
    if (dsu.parent(a) == dsu.parent(b)) continue;
    res += dist(make_pair(a, b));
    dsu.join(a, b);
    if (alive.count(a)) add(a);
    if (alive.count(b)) add(b);
  }
  cout << res << endl;
  return 0;
}
