#include <bits/stdc++.h>
const int inf = 103974182;
using namespace std;
int n;
pair<int, pair<int, int> > a[200005];
vector<pair<int, pair<int, int> > > vec;
set<pair<int, pair<int, int> > > squ;
int f[200005];
priority_queue<pair<int, pair<int, int> >, vector<pair<int, pair<int, int> > >,
               greater<pair<int, pair<int, int> > > >
    que;
int find(int x) { return (x == f[x] ? x : f[x] = find(f[x])); }
int add(int x, int y) {
  x = find(x);
  y = find(y);
  if (rand() & 1)
    f[x] = y;
  else
    f[y] = x;
}
bool compare1(pair<int, pair<int, int> > a, pair<int, pair<int, int> > b) {
  return a.second.first < b.second.first;
}
bool compare2(pair<int, pair<int, int> > a, pair<int, pair<int, int> > b) {
  return a.second.second < b.second.second;
}
void init() {
  for (int i = 0; i < 200005; i++) {
    f[i] = i;
  }
}
int main() {
  cin >> n;
  for (int i = 0; i < n; i++) {
    scanf("%d%d", &a[i].second.first, &a[i].second.second);
    a[i].first = i;
  }
  sort(a, a + n, compare1);
  for (int i = 0; i < n - 1; i++) {
    vec.push_back(
        make_pair(min(abs(a[i + 1].second.first - a[i].second.first),
                      abs(a[i + 1].second.second - a[i].second.second)),
                  make_pair(a[i].first, a[i + 1].first)));
  }
  sort(a, a + n, compare2);
  for (int i = 0; i < n - 1; i++) {
    vec.push_back(
        make_pair(min(abs(a[i + 1].second.first - a[i].second.first),
                      abs(a[i + 1].second.second - a[i].second.second)),
                  make_pair(a[i].first, a[i + 1].first)));
  }
  init();
  int k = 0;
  long long ans = 0;
  int len = vec.size();
  for (int i = 0; i < len; i++) {
    if (k == n - 1) break;
    pair<int, pair<int, int> > t = vec[i];
    if (find(t.second.first) == find(t.second.second)) continue;
    k++;
    ans += t.first;
    add(t.second.first, t.second.second);
  }
  cout << ans << endl;
  return 0;
}
