#include <bits/stdc++.h>
using namespace std;
int par[10003];
int anc(int p) {
  if (par[p] == p) return p;
  return par[p] = anc(par[p]);
}
void join(int p, int q) { par[anc(p)] = anc(q); }
vector<pair<int, int> > vtxCood1, vtxCood2;
vector<pair<int, pair<int, int> > > vtxCood;
int n;
int main() {
  int x, y, ans = 0;
  cin >> n;
  for (int i = 1; i <= n; i++) par[i] = i;
  for (int i = 1; i <= n; i++) {
    scanf("%d%d", &x, &y);
    vtxCood1.push_back(pair<int, int>(x, i));
    vtxCood2.push_back(pair<int, int>(y, i));
  }
  sort(vtxCood1.begin(), vtxCood1.end());
  sort(vtxCood2.begin(), vtxCood2.end());
  for (int i = 0; i <= n - 2; i++) {
    vtxCood.push_back(pair<int, pair<int, int> >(
        vtxCood1[i + 1].first - vtxCood1[i].first,
        pair<int, int>(vtxCood1[i].second, vtxCood1[i + 1].second)));
    vtxCood.push_back(pair<int, pair<int, int> >(
        vtxCood2[i + 1].first - vtxCood2[i].first,
        pair<int, int>(vtxCood2[i].second, vtxCood2[i + 1].second)));
  }
  sort(vtxCood.begin(), vtxCood.end());
  vector<pair<int, pair<int, int> > >::iterator it;
  for (it = vtxCood.begin(); it != vtxCood.end(); it++) {
    int v1 = it->second.first;
    int v2 = it->second.second;
    if (anc(v1) != anc(v2)) {
      join(v1, v2);
      ans += it->first;
    }
  }
  cout << ans;
}
