#include <bits/stdc++.h>
using namespace std;
const int MAX_N = 100010;
const double eps = 1e-6;
const long long mod = 1000000007;
const int inf = 1 << 30;
void Debug() { cout << '\n'; }
template <class FIRST, class... REST>
void Debug(FIRST arg, REST... rest) {
  cout << arg << " ";
  Debug(rest...);
}
template <class T>
ostream& operator<<(ostream& out, const vector<T>& v) {
  out << "[";
  if (!v.empty()) {
    for (int i = 0; i < (int)v.size() - 1; i++) out << v[i] << ", ";
    out << v.back();
  }
  out << "]";
  return out;
}
template <class S, class T>
ostream& operator<<(ostream& out, const pair<S, T>& v) {
  out << "(" << v.first << ", " << v.second << ")";
  return out;
}
int N, E;
int par[MAX_N];
int ran[MAX_N];
void init(int n) {
  for (int i = 0; i < n; i++) {
    par[i] = i;
    ran[i] = 0;
  }
}
int find(int x) {
  if (par[x] == x) {
    return x;
  } else
    return par[x] = find(par[x]);
}
void unite(int x, int y) {
  x = find(x);
  y = find(y);
  if (x == y) return;
  if (ran[x] < ran[y]) {
    par[x] = y;
  } else {
    par[y] = x;
    if (ran[x] == ran[y]) ran[x]++;
  }
}
bool same(int x, int y) { return find(x) == find(y); }
struct edge {
  int u, v, cost;
};
bool comp(const edge& e1, const edge& e2) { return e1.cost < e2.cost; }
edge es[100010];
int kruskal() {
  sort(es, es + E, comp);
  init(N);
  int res = 0;
  for (int i = 0; i < E; i++) {
    edge e = es[i];
    if (!same(e.u, e.v)) {
      unite(e.u, e.v);
      res += e.cost;
    }
  }
  return res;
}
void add_edge(int s, int t, int cost) { es[E++] = edge{s, t, cost}; }
pair<int, int> X[MAX_N], Y[MAX_N];
void solve() {
  cin >> N;
  for (int i = 0; i < N; i++) {
    int a, b;
    cin >> a >> b;
    X[i] = pair<int, int>(a, i);
    Y[i] = pair<int, int>(b, i);
  }
  sort(X, X + N);
  sort(Y, Y + N);
  for (int i = 0; i < N - 1; i++) {
    add_edge(X[i].second, X[i + 1].second, X[i + 1].first - X[i].first);
    add_edge(Y[i].second, Y[i + 1].second, Y[i + 1].first - Y[i].first);
  }
  cout << kruskal() << "\n";
}
int main() {
  ios::sync_with_stdio(false);
  cin.tie(0);
  cout << fixed;
  cout.precision(20);
  solve();
  return 0;
}
