#include <bits/stdc++.h>
using namespace std;
struct LessFirst {
  bool operator()(const pair<long, int>& x, const pair<long, int>& y) const {
    return x.first < y.first;
  }
};
using PairSet = set<pair<long, int>, LessFirst>;
tuple<long, int, int> findMin(const PairSet& S, const PairSet& T) {
  if (S.size() > T.size()) {
    long diff;
    int s, t;
    tie(diff, t, s) = findMin(T, S);
    return {diff, s, t};
  }
  long bdiff = numeric_limits<long>::max();
  int bs = -1;
  int bt = -1;
  for (auto pr : S) {
    long vs;
    int s;
    tie(vs, s) = pr;
    PairSet::const_iterator lb, ub;
    tie(lb, ub) = T.equal_range({vs, -1});
    if (lb != ub) {
      bdiff = 0;
      bs = s;
      bt = lb->second;
      break;
    }
    if (lb != T.begin()) {
      --lb;
      if (bdiff > vs - lb->first) {
        bdiff = vs - lb->first;
        bs = s;
        bt = lb->second;
      }
    }
    if (ub != T.end()) {
      if (bdiff > ub->first - vs) {
        bdiff = ub->first - vs;
        bs = s;
        bt = ub->second;
      }
    }
  }
  return {bdiff, bs, bt};
}
int main() {
  int N;
  cin >> N;
  vector<long> X(N);
  vector<long> Y(N);
  for (int i = 0; i < N; ++i) cin >> X[i] >> Y[i];
  set<int> added;
  set<int> notAdded;
  added.insert(0);
  for (int i = 1; i < N; ++i) {
    notAdded.insert(i);
  }
  PairSet addedX;
  PairSet notAddedX;
  addedX.insert({X[0], 0});
  for (int i = 1; i < N; ++i) {
    notAddedX.insert({X[i], i});
  }
  PairSet addedY;
  PairSet notAddedY;
  addedY.insert({Y[0], 0});
  for (int i = 1; i < N; ++i) {
    notAddedY.insert({Y[i], i});
  }
  long total = 0;
  while ((int)added.size() < N) {
    long xdiff;
    int xs, xt;
    tie(xdiff, xs, xt) = findMin(addedX, notAddedX);
    long ydiff;
    int ys, yt;
    tie(ydiff, ys, yt) = findMin(addedY, notAddedY);
    long diff = xdiff;
    int t = xt;
    if (ydiff < xdiff) {
      diff = ydiff;
      t = yt;
    }
    total += diff;
    notAdded.erase(t);
    added.insert(t);
    notAddedX.erase({X[t], t});
    addedX.insert({X[t], t});
    notAddedY.erase({Y[t], t});
    addedY.insert({Y[t], t});
  }
  cout << total << '\n';
  return 0;
}
