#include <bits/stdc++.h>
using namespace std;
vector<pair<int, int>> p;
int main() {
  ios_base::sync_with_stdio(false);
  cin.tie(NULL);
  long long n;
  cin >> n;
  p.resize(n);
  vector<pair<long long, long long>> x(n);
  vector<pair<long long, long long>> y(n);
  vector<pair<long long, pair<long long, long long>>> g;
  for (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 (int i = 0; i < n - 1; i++)
    g.push_back(make_pair(abs(x[i].first - x[i + 1].first),
                          make_pair(x[i].second, x[i + 1].second)));
  for (int i = 0; i < n - 1; i++)
    g.push_back(make_pair(abs(y[i].first - y[i + 1].first),
                          make_pair(y[i].second, y[i + 1].second)));
  sort((g).begin(), (g).end());
  vector<int> tree_id(n, 0);
  for (int i = 0; i < n; i++) tree_id[i] = i;
  long long m = g.size();
  long long cost = 0;
  for (int i = 0; i < m; 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;
      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;
  return 0;
}
