#include <bits/stdc++.h>
using namespace std;
struct union_find {
  const int root_v = -1;
  vector<int> d;
  union_find(int n) : d(n, root_v) {}
  int root(int i) { return d[i] == root_v ? i : root(d[i]); }
  bool is_connect(int i, int j) { return root(i) == root(j); }
  void connect(int i, int j) { d[i] = j; }
};
struct city {
  int index;
  int x;
  int y;
};
struct path {
  int s, g;
  int cost;
};
int main() {
  cin.tie(0);
  ios::sync_with_stdio(false);
  long n;
  cin >> n;
  vector<city> cs(n);
  for (int i = 0; i < n; i++) {
    cs[i].index = i;
    cin >> cs[i].x >> cs[i].y;
  }
  vector<path> e;
  sort(cs.begin(), cs.end(), [](city r, city l) { return r.x < l.x; });
  for (int i = 0; i < cs.size() - 1; i++) {
    e.push_back(path{cs[i].index, cs[i + 1].index, cs[i + 1].x - cs[i].x});
  }
  sort(cs.begin(), cs.end(), [](city r, city l) { return r.y < l.y; });
  for (int i = 0; i < cs.size() - 1; i++) {
    e.push_back(path{cs[i].index, cs[i + 1].index, cs[i + 1].y - cs[i].y});
  }
  sort(e.begin(), e.end(), [](path r, path l) { return r.cost < l.cost; });
  int cost = 0;
  union_find uf(n);
  for (path p : e) {
    if (!uf.is_connect(p.s, p.g)) {
      uf.connect(p.s, p.g);
      cost += p.cost;
    }
  }
  cout << cost << endl;
  return 0;
}
