#include <bits/stdc++.h>
using namespace std;
const int MAX_N = 1e5 + 1;
pair<long long, int> X[MAX_N], Y[MAX_N];
int N;
struct UF {
 public:
  int groupNum;
  UF(int N) {
    uf = vector<int>(N);
    rank = vector<int>(N);
    for (int i = 0; i < N; ++i) uf[i] = i, rank[i] = 0;
    groupNum = N;
  }
  int find(int i) { return uf[i] == i ? i : uf[i] = find(uf[i]); }
  bool same(int x, int y) { return find(x) == find(y); }
  void unite(int x, int y) {
    x = find(x);
    y = find(y);
    if (x == y) return;
    groupNum--;
    if (rank[x] == rank[y]) {
      uf[x] = y;
      rank[y]++;
      return;
    }
    if (rank[x] < rank[y]) {
      uf[x] = y;
    } else {
      uf[y] = x;
      if (rank[x] == rank[y]) ++rank[x];
    }
  }

 private:
  vector<int> rank;
  vector<int> uf;
};
long long solve() {
  sort(X, X + N), sort(Y, Y + N);
  vector<tuple<long long, int, int>> XX, YY;
  for (int i = 0; i < (N - 1); ++i) {
    XX.emplace_back(X[i + 1].first - X[i].first, X[i + 1].second, X[i].second);
    YY.emplace_back(Y[i + 1].first - Y[i].first, Y[i + 1].second, Y[i].second);
  }
  sort(XX.begin(), XX.end()), sort(YY.begin(), YY.end());
  long long res = 0;
  UF uf(N);
  int i = 0, j = 0;
  while (i < N || j < N) {
    tuple<long long, int, int> a;
    if (i == N)
      a = YY[j++];
    else if (j == N)
      a = XX[i++];
    else {
      if (XX[i] < YY[j])
        a = XX[i++];
      else
        a = YY[j++];
    }
    long long d;
    int u, v;
    tie(d, u, v) = a;
    if (uf.same(u, v)) continue;
    res += d;
    uf.unite(u, v);
  }
  return res;
}
int main() {
  ios_base::sync_with_stdio(false);
  cin.tie(0);
  cin >> N;
  for (int i = 0; i < (N); ++i) {
    int x, y;
    cin >> x >> y;
    X[i] = {x, i}, Y[i] = {y, i};
  }
  cout << solve() << endl;
  return 0;
}
