#include <bits/stdc++.h>
#pragma GCC optimize("Ofast")
using namespace std;
template <class T>
using V = vector<T>;
using Graph = vector<vector<int>>;
using P = pair<long long, long long>;
template <class T>
inline bool chmin(T& a, T b) {
  if (a > b) {
    a = b;
    return true;
  }
  return false;
}
template <class T>
inline bool chmax(T& a, T b) {
  if (a < b) {
    a = b;
    return true;
  }
  return false;
}
const long long INF = 1e18;
const int max_E = 100005;
struct UnionFind {
  vector<int> par;
  UnionFind(int N) : par(N) {
    for (int i = 0; i < N; i++) par[i] = i;
  }
  int root(int x) {
    if (par[x] == x) return x;
    return par[x] = root(par[x]);
  }
  void unite(int x, int y) {
    int rx = root(x);
    int ry = root(y);
    if (rx == ry) return;
    par[rx] = ry;
  }
  bool same(int x, int y) {
    int rx = root(x);
    int ry = root(y);
    return rx == ry;
  }
};
struct edge {
  int u, v;
  long long cost;
};
bool comp(const edge& e1, const edge& e2) { return e1.cost < e2.cost; }
edge es[max_E];
int N, M;
long long kruskal() {
  sort(es, es + M, comp);
  UnionFind tree(N);
  long long res = 0;
  for (int i = 0; i < M; i++) {
    edge e = es[i];
    if (!tree.same(e.u, e.v)) {
      tree.unite(e.u, e.v);
      res += e.cost;
    }
  }
  return res;
}
signed main() {
  cin >> N;
  M = 2 * N - 2;
  V<pair<long long, pair<long long, int>>> p(N), q(N);
  for (int i = 0; i < N; i++) {
    long long x, y;
    cin >> x >> y;
    p[i] = make_pair(x, make_pair(y, i));
    q[i] = make_pair(y, make_pair(x, i));
  }
  sort((p).begin(), (p).end());
  sort((q).begin(), (q).end());
  V<pair<long long, pair<int, int>>> pq;
  for (int i = 0; i < N - 1; i++) {
    pq.push_back(
        make_pair(p[i + 1].first - p[i].first,
                  make_pair(p[i + 1].second.second, p[i].second.second)));
    pq.push_back(
        make_pair(q[i + 1].first - q[i].first,
                  make_pair(q[i + 1].second.second, q[i].second.second)));
  }
  sort((pq).begin(), (pq).end());
  for (int i = 0; i < 2 * N - 2; i++) {
    es[i].u = pq[i].second.first;
    es[i].v = pq[i].second.second;
    es[i].cost = pq[i].first;
  }
  cout << kruskal() << endl;
}
