#include <bits/stdc++.h>
using namespace std;
long long int mpow(long long int a, long long int b) {
  if (b == 0)
    return 1;
  else if (b % 2 == 0) {
    long long int memo = mpow(a, b / 2);
    return memo * memo % (long long int)(1e9 + 7);
  } else
    return mpow(a, b - 1) * a % (long long int)(1e9 + 7);
}
long long int gcd(long long int a, long long int b) {
  if (b == 0)
    return a;
  else
    return gcd(b, a % b);
}
vector<long long int> kaijo_memo;
long long int kaijo(long long int n) {
  if (kaijo_memo.size() > n) return kaijo_memo[n];
  if (kaijo_memo.size() == 0) kaijo_memo.push_back(1);
  while (kaijo_memo.size() <= n)
    kaijo_memo.push_back(kaijo_memo[kaijo_memo.size() - 1] * kaijo_memo.size() %
                         (long long int)(1e9 + 7));
  return kaijo_memo[n];
}
long long int nCr(long long int n, long long int r) {
  if (n < r || r < 0) return 0;
  long long int ret = 1;
  ret *= kaijo(n);
  ret %= (long long int)(1e9 + 7);
  ret *= mpow(kaijo(r), (long long int)(1e9 + 7) - 2);
  ret %= (long long int)(1e9 + 7);
  ret *= mpow(kaijo(n - r), (long long int)(1e9 + 7) - 2);
  ret %= (long long int)(1e9 + 7);
  return ret;
}
struct edge {
  long long int cost;
  int a, b;
};
int parent[(int)1e5 + 3];
int find(int a) {
  if (parent[a] == a) {
    return a;
  } else {
    return parent[a] = find(parent[a]);
  }
}
void unite(int a, int b) {
  int pa = find(a);
  int pb = find(b);
  if (pa == pb) return;
  parent[pa] = pb;
  return;
}
vector<edge> G;
int main(void) {
  int n;
  cin >> n;
  for (int i = 0; i < (int)(n); i++) {
    parent[i] = i;
  }
  int x, y;
  vector<pair<int, int>> xs, ys;
  for (int i = 0; i < (int)(n); i++) {
    cin >> x >> y;
    xs.push_back(pair<int, int>{x, i});
    ys.push_back(pair<int, int>{y, i});
  }
  sort(xs.begin(), xs.end());
  sort(ys.begin(), ys.end());
  for (int i = 0; i < (int)(n - 1); i++) {
    G.push_back(
        edge{xs[i + 1].first - xs[i].first, xs[i].second, xs[i + 1].second});
    G.push_back(
        edge{ys[i + 1].first - ys[i].first, ys[i].second, ys[i + 1].second});
  }
  sort(G.begin(), G.end(), [](edge& a, edge& b) { return a.cost < b.cost; });
  int count = 0;
  long long int ans = 0;
  for (int i = 0; i < (int)(G.size()); i++) {
    long long int cost = G[i].cost;
    int a = G[i].a;
    int b = G[i].b;
    if (find(a) == find(b)) {
      continue;
    }
    ans += cost;
    unite(a, b);
    count++;
    if (count == n - 1) break;
  }
  cout << ans << endl;
  return 0;
}
