#include <bits/stdc++.h>
using namespace std;
template <typename T1, typename T2>
using P = pair<T1, T2>;
template <typename T>
using V = vector<T>;
struct edge {
  long long int from, to;
  long long int cost;
};
bool operator<(const edge& edge1, const edge& edge2) {
  return edge1.cost < edge2.cost;
};
const long long int INF = 1e18;
const long long int MOD = 1e9 + 7;
template <typename T>
ostream& operator<<(ostream& s, const V<T>& v) {
  s << "[";
  for (long long int i = 0; i < v.size(); i++) {
    s << v[i];
    if (i < v.size() - 1) s << " ";
  }
  s << "]";
  return s;
}
template <typename T1, typename T2>
ostream& operator<<(ostream& s, const P<T1, T2>& p) {
  s << "(" << p.first << "," << p.second << ")";
  return s;
}
class UnionFind {
 private:
  vector<long long int> par, myrank;

 public:
  UnionFind(long long int n) {
    par.resize(n);
    myrank.resize(n, 0);
    for (long long int i = 0; i < n; i++) {
      par[i] = i;
    }
  }
  long long int find(long long int x) {
    if (par[x] == x) return x;
    return par[x] = find(par[x]);
  }
  void unite(long long int x, long long int y) {
    x = find(x);
    y = find(y);
    if (x == y) return;
    if (myrank[x] < myrank[y]) {
      par[x] = y;
    } else {
      par[y] = x;
      if (myrank[x] == myrank[y]) myrank[x]++;
    }
  }
  bool same(long long int x, long long int y) { return find(x) == find(y); }
};
long long int kruskal(vector<edge>& E, long long int N) {
  vector<bool> used(N, false);
  UnionFind uni(used.size());
  sort((E).begin(), (E).end());
  long long int sum = 0;
  for (long long int i = 0; i < E.size(); i++) {
    edge e = E[i];
    if (!uni.same(e.from, e.to)) {
      uni.unite(e.from, e.to);
      sum += e.cost;
      used[i] = true;
    }
  }
  return sum;
}
signed main() {
  long long int N;
  cin >> N;
  V<P<long long int, long long int>> x(N), y(N);
  for (long long int i = (0); i < (N); ++i) {
    long long int s, t;
    cin >> s >> t;
    x[i] = make_pair(s, i);
    y[i] = make_pair(t, i);
  }
  sort((x).begin(), (x).end());
  sort((y).begin(), (y).end());
  V<edge> E;
  for (long long int i = (0); i < (N - 1); ++i) {
    E.push_back(
        (edge){x[i].second, x[i + 1].second, x[i + 1].first - x[i].first});
    E.push_back(
        (edge){y[i].second, y[i + 1].second, y[i + 1].first - y[i].first});
  }
  long long int ans = kruskal(E, N);
  cout << ans << endl;
  return 0;
}
