#include <bits/stdc++.h>
using namespace std;
int n;
int par[100005], ran[100005];
void init(int n) {
  for (int i = 0; i < (n); i++) {
    par[i] = i;
    ran[i] = 0;
  }
}
int find(int x) {
  if (par[x] == x)
    return x;
  else
    return par[x] = find(par[x]);
}
void unite(int x, int y) {
  x = find(x);
  y = find(y);
  if (x == y) return;
  if (ran[x] < ran[y])
    par[x] = y;
  else {
    par[y] = x;
    if (ran[x] == ran[y]) ran[x]++;
  }
}
bool same(int x, int y) { return find(x) == find(y); }
int main(int argc, char const *argv[]) {
  ios_base::sync_with_stdio(false);
  cin >> n;
  vector<pair<int, int> > px(n), py(n);
  vector<pair<int, pair<int, int> > > p(n);
  for (int i = 0; i < (n); i++) {
    int x, y;
    cin >> x >> y;
    px[i] = make_pair(x, i);
    py[i] = make_pair(y, i);
    p[i].first = 1000000005;
  }
  sort(px.begin(), px.end());
  sort(py.begin(), py.end());
  for (int i = 1; i < n; i++) {
    int dif = abs(px[i].first - px[i - 1].first);
    if (p[px[i].second].first > dif) {
      p[px[i].second].first = dif;
      p[px[i].second].second.first = px[i].second;
      p[px[i].second].second.second = px[i - 1].second;
    }
    if (p[px[i - 1].second].first > dif) {
      p[px[i - 1].second].first = dif;
      p[px[i - 1].second].second.first = px[i - 1].second;
      p[px[i - 1].second].second.second = px[i].second;
    }
    dif = abs(py[i].first - py[i - 1].first);
    if (p[py[i].second].first > dif) {
      p[py[i].second].first = dif;
      p[py[i].second].second.first = py[i].second;
      p[py[i].second].second.second = py[i - 1].second;
    }
    if (p[py[i - 1].second].first > dif) {
      p[py[i - 1].second].first = dif;
      p[py[i - 1].second].second.first = py[i - 1].second;
      p[py[i - 1].second].second.second = py[i].second;
    }
  }
  sort(p.begin(), p.end());
  init(n);
  int ans = 0;
  for (int i = 0; i < (n); i++) {
    if (same(p[i].second.first, p[i].second.second)) continue;
    ans += p[i].first;
    unite(p[i].second.first, p[i].second.second);
  }
  cout << ans << endl;
  return 0;
}
