#include <bits/stdc++.h>
using namespace std;
const int CITY_MAX = 100000;
typedef struct {
  int x;
  int y;
  int num;
  int connect[4];
  int joint;
} City;
int main() {
  int N, x, y, cost = 0, cng, cit;
  static City city[CITY_MAX];
  static pair<int, int> xNear[CITY_MAX], yNear[CITY_MAX];
  static pair<int, pair<int, int> > root[2 * CITY_MAX];
  queue<int> que;
  cin >> N;
  for (int i = 0; i < N; i++) {
    cin >> x >> y;
    xNear[i] = make_pair(x, i);
    yNear[i] = make_pair(y, i);
    city[i].x = x;
    city[i].y = y;
    city[i].num = i;
    city[i].joint = 0;
  }
  sort(xNear, xNear + N);
  sort(yNear, yNear + N);
  for (int i = 1; i < N; i++) {
    root[i - 1] = make_pair(xNear[i].first - xNear[i - 1].first,
                            make_pair(xNear[i].second, xNear[i - 1].second));
    root[N + i - 2] =
        make_pair(yNear[i].first - yNear[i - 1].first,
                  make_pair(yNear[i].second, yNear[i - 1].second));
  }
  sort(root, root + 2 * N - 2);
  for (int i = 0; i < 2 * N - 2; i++) {
    if (city[root[i].second.first].num != city[root[i].second.second].num) {
      cost += root[i].first;
      cng = city[root[i].second.first].num;
      que.push(root[i].second.second);
      while (!que.empty()) {
        cit = que.front();
        que.pop();
        if (city[cit].num - cng) {
          city[cit].num = cng;
          for (int j = 0; j < city[cit].joint; j++)
            que.push(city[cit].connect[j]);
        }
      }
      city[root[i].second.first].connect[city[root[i].second.first].joint] =
          root[i].second.second;
      city[root[i].second.first].joint++;
      city[root[i].second.second].connect[city[root[i].second.second].joint] =
          root[i].second.first;
      city[root[i].second.second].joint++;
    } else {
    }
  }
  cout << cost;
  return 0;
}
