#include <bits/stdc++.h>
using namespace std;
int n, ans;
pair<int, int> xx[100005], yy[100005], val[100005], nei[100005];
int roadx[100005], roady[100005];
int par[100005];
int pr(int x) {
  if (x == par[x])
    return x;
  else
    return pr(par[x]);
}
int Ab(int x) {
  if (x < 0) return -x;
  return x;
}
int main() {
  cin >> n;
  for (int i = 1; i <= n; i++) par[i] = i;
  for (int i = 1; i <= n; i++) {
    int x, y;
    cin >> x >> y;
    xx[i] = make_pair(x, i);
    yy[i] = make_pair(y, i);
    roadx[i] = x;
    roady[i] = y;
  }
  sort(xx + 1, xx + n + 1);
  sort(yy + 1, yy + n + 1);
  int cnt = 0;
  for (int i = 1; i < n; i++) {
    val[cnt] = make_pair(min(Ab(xx[i + 1].first - xx[i].first),
                             Ab(roady[xx[i + 1].second] - roady[xx[i].second])),
                         cnt);
    nei[cnt++] = make_pair(xx[i + 1].second, xx[i].second);
    val[cnt] = make_pair(min(Ab(yy[i + 1].first - yy[i].first),
                             Ab(roadx[yy[i + 1].second] - roadx[yy[i].second])),
                         cnt);
    nei[cnt++] = make_pair(yy[i + 1].second, yy[i].second);
  }
  sort(val, val + cnt);
  for (int i = 0; i < cnt; i++) {
    int now = val[i].second;
    int x = nei[now].first;
    int y = nei[now].second;
    x = pr(x);
    y = pr(y);
    if (x != y) {
      par[x] = y;
      ans += val[i].first;
    }
  }
  cout << ans << endl;
  return 0;
}
