#include <bits/stdc++.h>
using namespace std;
int n;
pair<pair<int, int>, int> a[111111];
vector<pair<int, pair<int, int> > > edge;
int f[111111];
int F(int a) { return f[a] == a ? a : f[a] = F(f[a]); }
int main() {
  ios::sync_with_stdio(false);
  cin.tie(0);
  cout.tie(0);
  ;
  for (int i = 0; i < 111111; i++) f[i] = i;
  cin >> n;
  for (int i = 0; i < n; i++) {
    cin >> a[i].first.first >> a[i].first.second;
    a[i].second = i;
  }
  for (int tot = 0; tot < 2; tot++) {
    sort(a, a + n);
    for (int i = 0; i < n - 1; i++) {
      edge.push_back({min(abs(a[i].first.first - a[i + 1].first.first),
                          abs(a[i].first.second - a[i + 1].first.second)),
                      {i, i + 1}});
      swap(a[i].first.first, a[i].first.second);
    }
  }
  sort(edge.begin(), edge.end());
  ;
  long long ans = 0;
  for (int i = 0; i < edge.size(); i++) {
    int a, b, c;
    c = edge[i].first;
    a = edge[i].second.first;
    b = edge[i].second.second;
    a = F(a);
    b = F(b);
    if (a == b) {
      continue;
    }
    ans += c;
    f[a] = b;
  }
  cout << ans << endl;
  return 0;
}
