#include <bits/stdc++.h>
using namespace std;
vector<pair<int, int> > G[100005];
bool used[10005];
vector<pair<int, int> > X;
vector<pair<int, int> > Y;
int N;
int prim() {
  for (int i = 0; i < N; i++) {
    used[i] = false;
  }
  int res = 0;
  priority_queue<pair<int, int>, vector<pair<int, int> >,
                 greater<pair<int, int> > >
      Q;
  Q.push(pair<int, int>(0, 0));
  while (!Q.empty()) {
    pair<int, int> q = Q.top();
    Q.pop();
    int p = q.second;
    int cost = q.first;
    if (used[p]) continue;
    res += cost;
    used[p] = true;
    for (int i = 0; i < G[p].size(); i++) {
      pair<int, int> next = G[p][i];
      Q.push(pair<int, int>(next.second, next.first));
    }
  }
  return res;
}
int main() {
  cin >> N;
  for (int i = 0; i < N; i++) {
    int x, y;
    cin >> x >> y;
    X.push_back(pair<int, int>(x, i));
    Y.push_back(pair<int, int>(y, i));
  }
  sort(X.begin(), X.end());
  sort(Y.begin(), Y.end());
  for (int i = 0; i < N - 1; i++) {
    G[X[i].second].push_back(
        pair<int, int>(X[i + 1].second, X[i + 1].first - X[i].first));
    G[Y[i].second].push_back(
        pair<int, int>(Y[i + 1].second, Y[i + 1].first - Y[i].first));
    G[X[i + 1].second].push_back(
        pair<int, int>(X[i].second, X[i + 1].first - X[i].first));
    G[Y[i + 1].second].push_back(
        pair<int, int>(Y[i].second, Y[i + 1].first - Y[i].first));
  }
  cout << prim() << endl;
  return 0;
}
