#include <bits/stdc++.h>
using namespace std;
inline int toInt(string s) {
  int v;
  istringstream sin(s);
  sin >> v;
  return v;
}
template <class T>
inline string toString(T x) {
  ostringstream sout;
  sout << x;
  return sout.str();
}
template <class T>
inline T sqr(T x) {
  return x * x;
}
const double EPS = 1e-10;
const double PI = acos(-1.0);
const long long MOD = (long long)1e9 + 7;
const long long MAX_V = 10003;
int V, E;
int par[MAX_V];
int rnk[MAX_V];
void init(int n) {
  for (int i = (0); i < (n); ++i) {
    par[i] = i;
    rnk[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 (rnk[x] < rnk[y]) {
    par[x] = y;
  } else {
    par[y] = x;
    if (rnk[x] == rnk[y]) rnk[x]++;
  }
}
bool same(int x, int y) { return find(x) == find(y); }
struct UnionFind {
  vector<int> par;
  int n, cnt;
  UnionFind(const int& x = 0) { init(x); }
  void init(const int& x) { par.assign(cnt = n = x, -1); }
  inline int find(const int& x) {
    return par[x] < 0 ? x : par[x] = find(par[x]);
  }
  inline bool same(const int& x, const int& y) { return find(x) == find(y); }
  inline bool unite(int x, int y) {
    if ((x = find(x)) == (y = find(y))) return false;
    --cnt;
    if (par[x] > par[y]) swap(x, y);
    par[x] += par[y];
    par[y] = x;
    return true;
  }
  inline int count() const { return cnt; }
  inline int count(int x) { return -par[find(x)]; }
};
struct edge {
  int u, v;
  long long cost;
};
vector<edge> es;
bool comp(const edge& e1, const edge& e2) { return e1.cost < e2.cost; }
long long kruskal() {
  sort(es.begin(), es.end(), comp);
  init(V);
  long long 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;
}
int main() {
  int N;
  cin >> N;
  V = N;
  vector<pair<long, long> > px, py;
  for (int i = (0); i < (N); ++i) {
    long long x, y;
    cin >> x >> y;
    px.emplace_back(make_pair(x, i));
    py.emplace_back(make_pair(y, i));
  }
  sort((px).begin(), (px).end());
  sort((py).begin(), (py).end());
  edge e;
  E = 0;
  for (int i = (0); i < (N - 1); ++i) {
    edge e;
    e.u = px[i].second;
    e.v = px[i + 1].second;
    e.cost = px[i + 1].first - px[i].first;
    es.emplace_back(e);
    E++;
    e.u = py[i].second;
    e.v = py[i + 1].second;
    e.cost = py[i + 1].first - py[i].first;
    es.emplace_back(e);
    E++;
  }
  cout << kruskal() << endl;
  return 0;
}
