#include <bits/stdc++.h>
using namespace std;
vector<int> parent;
int dsu_get(int v) {
  return (v == parent[v]) ? v : (parent[v] = dsu_get(parent[v]));
}
void dsu_unite(int a, int b) {
  a = dsu_get(a);
  b = dsu_get(b);
  if (rand() & 1) swap(a, b);
  if (a != b) parent[a] = b;
}
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);
  parent.resize(n);
  for (int i = 0; i < n; ++i) parent[i] = i;
  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) parent[i] = i;
  int cost = 0;
  int m = g.size();
  for (int i = 0; i < m; ++i) {
    int a = g[i].second.first, b = g[i].second.second, l = g[i].first;
    if (dsu_get(a) != dsu_get(b)) {
      cost += l;
      dsu_unite(a, b);
    }
  }
  cout << cost;
  return 0;
}
