#include <bits/stdc++.h>
using namespace std;
struct disset {
  int data, rank, parent;
};
int find_set(struct disset *sets, int node) {
  if (sets[node].parent != node)
    sets[node].parent = find_set(sets, sets[node].parent);
  return sets[node].parent;
}
void merge_set(struct disset *sets, int x, int y) {
  int xparent = find_set(sets, x);
  int yparent = find_set(sets, y);
  if (sets[xparent].rank > sets[yparent].rank)
    sets[yparent].parent = xparent;
  else if (sets[xparent].rank < sets[yparent].rank)
    sets[xparent].parent = yparent;
  else {
    sets[xparent].parent = yparent;
    sets[yparent].rank++;
  }
}
int main() {
  ios_base::sync_with_stdio(false);
  cin.tie(0);
  cout.tie(0);
  int TESTS = 1;
  while (TESTS--) {
    int n;
    cin >> n;
    vector<pair<long long int, long long int> > x(n), y(n);
    vector<pair<long long, pair<long long int, long long int> > > a;
    for (long long int i = 0; i < n; i++) {
      cin >> x[i].first >> y[i].first;
      x[i].second = i;
      y[i].second = i;
    }
    sort((x).begin(), (x).end());
    sort((y).begin(), (y).end());
    for (long long int i = 1; i < n; i++) {
      a.push_back(
          {x[i].first - x[i - 1].first, {x[i].second, x[i - 1].second}});
      a.push_back(
          {y[i].first - y[i - 1].first, {y[i].second, y[i - 1].second}});
    }
    sort((a).begin(), (a).end());
    disset sets[n];
    for (long long int i = 0; i < n; i++) {
      sets[i].data = i;
      sets[i].parent = i;
      sets[i].rank = 0;
    }
    long long ans = 0;
    for (long long int i = 0; i < (long long int)a.size(); i++) {
      if (find_set(sets, a[i].second.first) !=
          find_set(sets, a[i].second.second)) {
        ans += a[i].first;
        merge_set(sets, a[i].second.first, a[i].second.second);
      }
    }
    cout << ans;
  }
  return 0;
}
