#include <bits/stdc++.h>
using namespace std;
struct st {
  int pos, id;
  st(int p, int i) : pos(p), id(i) {}
};
struct st2 {
  int f, t, l;
  st2(int _f, int _t, int _l) : f(_f), t(_t), l(_l) {}
};
void marge_label(vector<int>& label, vector<vector<int> >& label_lst, int x,
                 int y) {
  for (int i = 0; i < label_lst[y].size(); ++i) {
    label_lst[x].push_back(label_lst[y][i]);
    label[label_lst[y][i]] = x;
  }
}
int main() {
  int n;
  cin >> n;
  vector<st> x, y;
  for (int i = 0; i < n; ++i) {
    int _x, _y;
    cin >> _x >> _y;
    x.push_back(st(_x, i));
    y.push_back(st(_y, i));
  }
  sort(x.begin(), x.end(), [](st a, st b) {
    if (a.pos == b.pos) return a.id < b.id;
    return a.pos < b.pos;
  });
  sort(y.begin(), y.end(), [](st a, st b) {
    if (a.pos == b.pos) return a.id < b.id;
    return a.pos < b.pos;
  });
  vector<st2> v;
  for (int i = 0; i < x.size() - 1; ++i) {
    v.push_back(st2(x[i].id, x[i + 1].id, x[i + 1].pos - x[i].pos));
  }
  for (int i = 0; i < y.size() - 1; ++i) {
    v.push_back(st2(y[i].id, y[i + 1].id, y[i + 1].pos - y[i].pos));
  }
  sort(v.begin(), v.end(), [](st2 a, st2 b) {
    if (a.l == b.l) return a.f < b.f;
    return a.l < b.l;
  });
  vector<int> label;
  vector<vector<int> > label_lst;
  for (int i = 0; i < n; ++i) {
    label.push_back(i);
    vector<int> lll;
    lll.push_back(i);
    label_lst.push_back(lll);
  }
  int sum = 0, selected = 0;
  for (int i = 0; i < v.size(); ++i) {
    if (label[v[i].f] == label[v[i].t]) continue;
    sum += v[i].l;
    selected++;
    marge_label(label, label_lst, label[v[i].f], label[v[i].t]);
  }
  cout << sum << endl;
  return 0;
}
