#include <bits/stdc++.h>
using namespace std;
bool gt(const pair<int, int> &a, const pair<int, int> &b) {
  return a.second < b.second;
}
bool gt2(const pair<pair<int, int>, int> &a,
         const pair<pair<int, int>, int> &b) {
  return a.second < b.second;
}
int group(vector<int> &did, int a) {
  while (did[a] >= 0) {
    a = did[a];
  }
  return a;
}
void unite(vector<int> &did, int a, int b) {
  a = group(did, a);
  b = group(did, b);
  did[b]--;
  did[a] = b;
}
int main() {
  int n;
  cin >> n;
  vector<pair<int, int> > x(n), y(n);
  vector<int> did(n);
  for (int i = 0; i < n; i++) {
    int xi, yi;
    cin >> xi >> yi;
    x[i] = pair<int, int>(i, xi);
    y[i] = pair<int, int>(i, yi);
    did[i] = -1;
  }
  sort(x.begin(), x.end(), gt);
  sort(y.begin(), y.end(), gt);
  vector<pair<pair<int, int>, int> > dx(n - 1), dy(n - 1);
  for (int i = 0; i < n - 1; i++) {
    dx[i] =
        pair<pair<int, int>, int>(pair<int, int>(x[i].first, x[i + 1].first),
                                  x[i + 1].second - x[i].second);
    dy[i] =
        pair<pair<int, int>, int>(pair<int, int>(y[i].first, y[i + 1].first),
                                  y[i + 1].second - y[i].second);
  }
  sort(dx.begin(), dx.end(), gt2);
  sort(dy.begin(), dy.end(), gt2);
  int dn = 0, px = 0, py = 0;
  long long sum = 0;
  while (dn < n - 1) {
    if (dx[px].second < dy[py].second) {
      if (group(did, dx[px].first.first) != group(did, dx[px].first.second)) {
        unite(did, dx[px].first.first, dx[px].first.second);
        sum += dx[px].second;
        dn++;
      } else {
      }
      px++;
    } else {
      if (group(did, dy[py].first.first) != group(did, dy[py].first.second)) {
        unite(did, dy[py].first.first, dy[py].first.second);
        sum += dy[py].second;
        dn++;
      } else {
      }
      py++;
    }
  }
  cout << sum << endl;
  return 0;
}
