#include <bits/stdc++.h>
#pragma comment(linker, "/stack:640000000")
using namespace std;
const double EPS = 1e-9;
const int INF = 0x7f7f7f7f;
const double PI = acos(-1.0);
template <class T>
inline T gcd(T a, T b) {
  return (b) == 0 ? (a) : gcd((b), ((a) % (b)));
}
template <class T>
inline T lcm(T a, T b) {
  return ((a) / gcd((a), (b)) * (b));
}
template <typename T>
string NumberToString(T Number) {
  ostringstream second;
  second << Number;
  return second.str();
}
struct debugger {
  template <typename T>
  debugger& operator,(const T& v) {
    cerr << v << " ";
    return *this;
  }
} dbg;
int t, n, m;
vector<pair<int, int> > x, y;
struct edge {
  int u, v, w;
  bool operator<(const edge& p) const { return w < p.w; }
};
int pr[300005];
int tot = 0;
vector<edge> e;
int find(int r) {
  if (pr[r] == r) return r;
  return pr[r] = find(pr[r]);
}
long long mst(int n) {
  sort(e.begin(), e.end());
  for (int i = 1; i <= n; i++) pr[i] = i;
  int count = 0;
  long long s = 0;
  for (int i = 0; i < (int)e.size(); i++) {
    int u = find(e[i].u);
    int v = find(e[i].v);
    if (u != v) {
      pr[u] = v;
      count++;
      s += e[i].w;
      if (count == n - 1) break;
    }
  }
  return s;
}
void addEdge(int u, int v, int cost) {
  edge get;
  get.u = u;
  get.v = v;
  get.w = cost;
  e.push_back(get);
}
map<pair<int, int>, int> mp;
int main() {
  while (scanf("%d", &n)) {
    tot = 0;
    mp.clear();
    x.clear();
    y.clear();
    e.clear();
    tot = 0;
    for (int i = 1; i <= (n); i++) {
      int a, b;
      scanf("%d%d", &a, &b);
      if (mp[pair<int, int>(a, b)]) continue;
      mp[pair<int, int>(a, b)] = 1;
      x.push_back(pair<int, int>(a, i));
      y.push_back(pair<int, int>(b, i));
      tot++;
    }
    sort(x.begin(), x.end());
    sort(y.begin(), y.end());
    for (int i = 0; i < (x.size()); i++) {
      if (i) {
        int v = x[i - 1].second;
        int cost = abs(x[i - 1].first - x[i].first);
        addEdge(x[i].second, v, cost);
      }
      if (i + 1 < x.size()) {
        int v = x[i + 1].second;
        int cost = abs(x[i + 1].first - x[i].first);
        addEdge(x[i].second, v, cost);
      }
    }
    for (int i = 0; i < (y.size()); i++) {
      if (i) {
        int v = y[i - 1].second;
        int cost = abs(y[i - 1].first - y[i].first);
        addEdge(y[i].second, v, cost);
      }
      if (i + 1 < y.size()) {
        int v = y[i + 1].second;
        int cost = abs(y[i + 1].first - y[i].first);
        addEdge(y[i].second, v, cost);
      }
    }
    printf("%lld\n", mst(tot));
  }
  return 0;
}
