#include <bits/stdc++.h>
using namespace std;
int n;
int x[200007], y[200007], fa[100007];
pair<int, int> xx[200007], yy[200007];
int root(int what) {
  if (fa[what] == what) return what;
  return fa[what] = root(fa[what]);
}
int gaoshi(int wha, int whb) {
  if (root(wha) == root(whb)) return 0;
  return 1;
}
int dist(int wha, int whb) {
  return min(abs(x[wha] - x[whb]), abs(y[wha] - y[whb]));
}
int main() {
  scanf("%d", &n);
  for (int i = 0; i < n; i++) {
    scanf("%d%d", x + i, y + i);
    fa[i] = i;
    xx[i] = make_pair(x[i], i);
    yy[i] = make_pair(y[i], i);
  }
  sort(xx, xx + n);
  sort(yy, yy + n);
  set<pair<int, pair<int, int> > > sp;
  for (int i = 0; i < n - 1; i++) {
    sp.insert(make_pair(dist(xx[i].first, xx[i + 1].first),
                        make_pair(xx[i].second, xx[i + 1].second)));
    sp.insert(make_pair(dist(yy[i].first, yy[i + 1].first),
                        make_pair(yy[i].second, yy[i + 1].second)));
  }
  long long ans = 0;
  while (((int)(sp).size())) {
    pair<int, pair<int, int> > bb = *(sp.begin());
    sp.erase(bb);
    ans += gaoshi(bb.second.first, bb.second.second) * bb.first;
  }
  printf("%I64d\n", ans);
  return 0;
}
