#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 main() {
  int n;
  cin >> n;
  vector<pair<int, int> > x(n), y(n);
  vector<bool> 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);
  }
  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) {
    if (dx[px].second < dy[py].second) {
      int num = 0;
      if (!did[dx[px].first.first]) {
        did[dx[px].first.first] = true;
        num++;
      }
      if (!did[dx[px].first.second]) {
        did[dx[px].first.second] = true;
        num++;
      }
      if (num > 0) {
        sum += dx[px].second;
        dn += num;
      } else {
        cout << "already connected" << endl;
      }
      px++;
    } else {
      int num = 0;
      if (!did[dy[py].first.first]) {
        did[dy[py].first.first] = true;
        num++;
      }
      if (!did[dy[py].first.second]) {
        did[dy[py].first.second] = true;
        num++;
      }
      if (num > 0) {
        sum += dy[py].second;
        dn += num;
      } else {
      }
      py++;
    }
  }
  cout << sum << endl;
  return 0;
}
