#include <bits/stdc++.h>
template <typename T>
bool chmax(T &a, T b) {
  if (a < b) {
    a = b;
    return true;
  }
  return false;
}
template <typename T>
bool chmin(T &a, T b) {
  if (a > b) {
    a = b;
    return true;
  }
  return false;
}
using namespace std;
using ll = long long int;
const int MOD = 1000000007;
const int INTMAX = 2147483647;
const ll LLMAX = 9223372036854775807;
bool comp(vector<ll> a, vector<ll> b) { return a[0] < b[0]; }
class UnionFind {
 public:
  vector<ll> par;
  UnionFind(ll N) : par(N) {
    for (ll i = 0; i < N; i++) par[i] = i;
  }
  ll root(ll x) {
    if (par[x] == x) return x;
    return par[x] = root(par[x]);
  }
  void unite(ll x, ll y) {
    int rx = root(x);
    int ry = root(y);
    if (rx == ry) return;
    par[rx] = ry;
  }
  bool same(ll x, ll y) {
    ll rx = root(x);
    ll ry = root(y);
    return rx == ry;
  }
};
bool comp4Kruskal(vector<ll> a, vector<ll> b) { return a[2] < b[2]; }
ll kruskal(vector<ll> s, vector<ll> t, vector<ll> c, ll N) {
  ll ret = 0;
  vector<vector<ll> > stc(s.size(), vector<ll>(3));
  for (ll i = 0; i < s.size(); i++) {
    stc[i][0] = s[i];
    stc[i][1] = t[i];
    stc[i][2] = c[i];
  }
  sort(stc.begin(), stc.end(), comp4Kruskal);
  UnionFind uf(N);
  for (ll i = 0; i < s.size(); i++) {
    if (!uf.same(stc[i][0], stc[i][1])) {
      uf.unite(stc[i][0], stc[i][1]);
      ret += stc[i][2];
    }
  }
  return ret;
}
int main() {
  ios::sync_with_stdio(false);
  cin.tie(0);
  ll N;
  cin >> N;
  vector<vector<ll> > x(N, vector<ll>(2)), y(N, vector<ll>(2));
  for (ll i = 0; i < N; i++) {
    cin >> x[i][0] >> y[i][0];
    x[i][1] = i;
    y[i][1] = i;
  }
  sort(x.begin(), x.end(), comp);
  sort(y.begin(), y.end(), comp);
  vector<vector<ll> > cost(N, vector<ll>(N, LLMAX));
  for (ll i = 0; i < N - 1; i++) {
    cost[x[i][1]][x[i + 1][1]] = x[i + 1][0] - x[i][0];
    cost[x[i + 1][1]][x[i][1]] = x[i + 1][0] - x[i][0];
  }
  for (ll i = 0; i < N - 1; i++) {
    cost[y[i][1]][y[i + 1][1]] = y[i + 1][0] - y[i][0];
    cost[y[i + 1][1]][y[i][1]] = y[i + 1][0] - y[i][0];
  }
  vector<ll> s(2 * N - 2), t(2 * N - 2), c(2 * N - 2);
  for (ll i = 0; i < N - 1; i++) {
    s[i] = x[i][1];
    t[i] = x[i + 1][1];
    c[i] = x[i + 1][0] - x[i][0];
  }
  for (ll i = 0; i < N - 1; i++) {
    s[i + N - 1] = y[i][1];
    t[i + N - 1] = y[i + 1][1];
    c[i + N - 1] = y[i + 1][0] - y[i][0];
  }
  cout << kruskal(s, t, c, N) << endl;
  return 0;
}
