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