#include <bits/stdc++.h>
using namespace std;
vector<pair<int, int> > a;
vector<pair<int, int> > b;
vector<pair<int, pair<int, int> > > g;
int main() {
  int n;
  cin >> n;
  for (int i = 0; i < n; i++) {
    int aa, bb;
    cin >> aa >> bb;
    a.push_back(make_pair(aa, i));
    b.push_back(make_pair(bb, i));
  }
  sort(a.begin(), a.end());
  sort(b.begin(), b.end());
  for (int i = n - 1; i > 0; i--) {
    g.push_back(make_pair((a[i].first - a[i - 1].first),
                          make_pair(a[i].second, a[i - 1].second)));
    g.push_back(make_pair((a[i].first - a[i - 1].first),
                          make_pair(a[i - 1].second, a[i].second)));
  }
  for (int i = n - 1; i > 0; i--) {
    g.push_back(make_pair((b[i].first - b[i - 1].first),
                          make_pair(b[i].second, b[i - 1].second)));
    g.push_back(make_pair((b[i].first - b[i - 1].first),
                          make_pair(b[i - 1].second, b[i].second)));
  }
  int cost = 0;
  vector<pair<int, int> > res;
  sort(g.begin(), g.end());
  vector<int> tree_id(n);
  for (int i = 0; i < n; ++i) tree_id[i] = i;
  for (int i = 0; i < ((int)(g).size()); ++i) {
    int a = g[i].second.first, b = g[i].second.second, l = g[i].first;
    if (tree_id[a] != tree_id[b]) {
      cost += l;
      res.push_back(make_pair(a, b));
      int old_id = tree_id[b], new_id = tree_id[a];
      for (int j = 0; j < n; ++j)
        if (tree_id[j] == old_id) tree_id[j] = new_id;
    }
  }
  cout << cost << endl;
}
