#include <bits/stdc++.h>
using namespace std;
pair<long long, long long> arr[100005], arr1[100005];
vector<pair<long long, pair<long long, long long> > > vect;
int root[100005];
int cnt[100005];
int findroot(int a) {
  while (a != root[a]) a = root[a];
  return a;
}
void uni(int a, int b) {
  int x = findroot(a);
  int y = findroot(b);
  if (cnt[x] > cnt[y]) {
    root[y] = x;
    cnt[x] += cnt[y];
  } else {
    root[x] = y;
    cnt[y] += cnt[x];
  }
}
int main() {
  for (int i = 0; i < 100005; i++) root[i] = i;
  int n;
  long long a, b;
  scanf("%d", &n);
  for (int i = 0; i < n; i++) {
    scanf("%lld%lld", &a, &b);
    arr[i].first = a;
    arr[i].second = i;
    arr1[i].first = b;
    arr1[i].second = i;
  }
  sort(arr, arr + n);
  for (int i = 0; i < n - 1; i++) {
    vect.push_back(make_pair((arr[i + 1].first - arr[i].first),
                             make_pair(arr[i + 1].second, arr[i].second)));
  }
  sort(arr1, arr1 + n);
  for (int i = 0; i < n - 1; i++) {
    vect.push_back(make_pair((arr1[i + 1].first - arr1[i].first),
                             make_pair(arr1[i + 1].second, arr1[i].second)));
  }
  long long ans = 0;
  int len = vect.size();
  sort(vect.begin(), vect.end());
  for (int i = 0; i < len; i++) {
    if (findroot(vect[i].second.first) != findroot(vect[i].second.second)) {
      uni(vect[i].second.first, vect[i].second.second);
      ans += vect[i].first;
    }
  }
  cout << ans << endl;
  return 0;
}
