#include <bits/stdc++.h>
using namespace std;
int N;
long long ans;
bool used[100010] = {0};
vector<pair<long long, int> > X, Y;
vector<pair<long long, int> > E[100020];
int main() {
  scanf("%d", &N);
  for (int i = 0; i < N; i++) {
    long long a, b;
    scanf("%lld%lld", &a, &b);
    X.push_back(make_pair(a, i));
    Y.push_back(make_pair(b, i));
  }
  sort(X.begin(), X.end());
  sort(Y.begin(), Y.end());
  for (int i = 0; i < X.size() - 1; i++) {
    long long xl = X[i + 1].first - X[i].first,
              yl = Y[i + 1].first - Y[i].first;
    E[X[i].second].push_back(make_pair(xl, X[i + 1].second));
    E[X[i + 1].second].push_back(make_pair(xl, X[i].second));
    E[Y[i].second].push_back(make_pair(yl, Y[i + 1].second));
    E[Y[i + 1].second].push_back(make_pair(yl, Y[i].second));
  }
  priority_queue<pair<long long, pair<int, long long> >,
                 vector<pair<long long, pair<int, long long> > >,
                 greater<pair<long long, pair<int, long long> > > >
      Q;
  Q.push(make_pair(0, make_pair(0, 0)));
  while (Q.size()) {
    pair<long long, pair<int, long long> > now = Q.top();
    Q.pop();
    if (used[now.second.first]) continue;
    used[now.second.first] = true;
    ans += now.second.second;
    for (int i = 0; i < E[now.second.first].size(); i++) {
      Q.push(make_pair(now.first + E[now.second.first][i].first,
                       make_pair(E[now.second.first][i].second,
                                 E[now.second.first][i].first)));
    }
  }
  printf("%lld\n", ans);
  return 0;
}
