#include <bits/stdc++.h>
using namespace std;
int t[101];
int pri[26];
int res = 0;
long long gcd(long long a, long long b) {
  if (b == 0) return a;
  return gcd(b, a % b);
}
int pr[100010];
void uini(int n) {
  for (size_t i = 0; i <= n; i++) {
    pr[i] = i;
  }
}
int parent(int x) {
  if (x == pr[x]) return x;
  return pr[x] = parent(pr[x]);
}
bool unit(int x, int y) {
  int px = parent(x);
  int py = parent(y);
  if (px == py) return false;
  if (px < py) {
    pr[y] = px;
  } else {
    pr[x] = py;
  }
  return true;
}
void solv() {
  int n;
  cin >> n;
  uini(n);
  pair<long long, int> xr[100010];
  pair<long long, int> yr[100010];
  for (size_t i = 0; i < n; i++) {
    long long x, y;
    cin >> x >> y;
    xr[i] = pair<long long, int>(x, i);
    yr[i] = pair<long long, int>(y, i);
  }
  sort(xr, xr + n);
  sort(yr, yr + n);
  map<long long, vector<pair<int, int>>> mx;
  for (size_t i = 1; i < n; i++) {
    long long rem = xr[i].first - xr[i - 1].first;
    mx[rem].push_back(pair<int, int>(xr[i].second, xr[i - 1].second));
    long long remy = yr[i].first - yr[i - 1].first;
    mx[remy].push_back(pair<int, int>(yr[i].second, yr[i - 1].second));
  }
  long long res = 0;
  for (map<long long, vector<pair<int, int>>>::iterator i = mx.begin();
       i != mx.end(); i++) {
    long long val = i->first;
    vector<pair<int, int>> v = i->second;
    for (size_t j = 0; j < v.size(); j++) {
      if (unit(v[j].first, v[j].second)) {
        res += val;
      }
    }
  }
  cout << res << endl;
}
int main() {
  solv();
  return 0;
}
