#include <bits/stdc++.h>
using namespace std;
const int mod = 1e9 + 7, A = 1e5 + 5;
long long rep[1005], sz[1005];
long long find(long long u) { return rep[u] == u ? u : rep[u] = find(rep[u]); }
bool join(long long a, long long b) {
  a = find(rep[a]), b = find(rep[b]);
  if (a == b) return false;
  if (sz[a] < sz[b]) swap(a, b);
  sz[a] += sz[b], sz[b] = 0;
  rep[b] = a;
  return true;
}
int main() {
  ios_base::sync_with_stdio(0);
  cin.tie(0);
  cout.tie(0);
  long long n;
  cin >> n;
  for (int i = 0; i < n; i++) rep[i] = i, sz[i] = 1;
  pair<long long, long long> arr[n + 1];
  vector<pair<long long, pair<long long, long long>>> byX, byY;
  for (int i = 0; i < n; i++)
    cin >> arr[i].first >> arr[i].second,
        byX.push_back({arr[i].first, {arr[i].second, i}}),
        byY.push_back({arr[i].second, {arr[i].first, i}});
  sort((byX).begin(), (byX).end()), sort((byY).begin(), (byY).end());
  map<long long, vector<pair<long long, long long>>> mp;
  for (int i = 1; i < n; i++) {
    mp[byX[i].first - byX[i - 1].first].push_back(
        {byX[i].second.second, byX[i - 1].second.second});
    mp[byY[i].first - byY[i - 1].first].push_back(
        {byY[i].second.second, byY[i - 1].second.second});
  }
  long long ans = 0;
  for (auto i : mp)
    for (auto j : i.second)
      if (join(j.first, j.second)) ans += i.first;
  cout << ans;
  return 0;
}
