#include <bits/stdc++.h>
using namespace std;
long long N;
pair<pair<long long, long long>, long long> px[100100];
pair<pair<long long, long long>, long long> py[100100];
vector<pair<long long, pair<long long, long long> > > edge;
struct UF {
  long long N;
  const static long long size = 100100;
  long long par[size];
  UF(long long n) {
    N = n;
    for (long long i = 0; i < (n); ++i) {
      par[i] = i;
    }
  }
  long long root(long long x) {
    if (par[x] == x) return x;
    return par[x] = root(par[x]);
  }
  void unite(long long x, long long y) {
    if (root(x) != root(y)) {
      par[x] = root(y);
    }
  }
  bool same(long long x, long long y) { return root(x) == root(y); }
};
signed main() {
  cin >> N;
  for (long long i = 0; i < (N); ++i) {
    long long x, y;
    cin >> x >> y;
    px[i] = pair<pair<long long, long long>, long long>(
        pair<long long, long long>(x, y), i);
    py[i] = pair<pair<long long, long long>, long long>(
        pair<long long, long long>(y, x), i);
  }
  sort(px, px + N);
  sort(py, py + N);
  for (long long i = 0; i < (N - 1); ++i) {
    long long x0 = px[i].first.first;
    long long x1 = px[i + 1].first.first;
    long long cost = x1 - x0;
    long long i0 = px[i].second;
    long long i1 = px[i + 1].second;
    edge.push_back(pair<long long, pair<long long, long long> >(
        cost, pair<long long, long long>(i0, i1)));
  }
  for (long long i = 0; i < (N - 1); ++i) {
    long long y0 = py[i].first.first;
    long long y1 = py[i + 1].first.first;
    long long cost = y1 - y0;
    long long i0 = py[i].second;
    long long i1 = py[i + 1].second;
    edge.push_back(pair<long long, pair<long long, long long> >(
        cost, pair<long long, long long>(i0, i1)));
  }
  sort(edge.begin(), edge.end());
  UF uf(N + 10);
  long long ans = 0;
  for (long long i = 0; i < (edge.size()); ++i) {
    pair<long long, long long> p = edge[i].second;
    if (!uf.same(p.first, p.second)) {
      ans += edge[i].first;
      uf.unite(p.first, p.second);
    }
  }
  cout << ans << endl;
  return 0;
}
