#include <bits/stdc++.h>
const int MXN = 2e5 + 1;
const long long MNN = 5e3 + 100;
const long long MOD = 1e9 + 7;
const long long INF = 1e18;
const int OO = 1e9 + 500;
using namespace std;
long long n, p[MXN], ans;
vector<pair<int, pair<int, int> > > q;
struct point {
  int x, y, ind;
} a[MXN];
bool cmp(point a, point b) { return a.x < b.x; }
bool cmp2(point a, point b) { return a.y < b.y; }
int batya(int x) {
  if (p[x] == x) {
    return x;
  }
  return batya(p[x]);
}
int main() {
  srand(time(0));
  cin >> n;
  for (int i = 1; i <= n; i++) {
    p[i] = i;
    cin >> a[i].x >> a[i].y;
    a[i].ind = i;
  }
  sort(a + 1, a + n + 1, cmp);
  for (int i = 1; i < n; i++) {
    q.push_back({a[i + 1].x - a[i].x, {a[i + 1].ind, a[i].ind}});
  }
  sort(a + 1, a + n + 1, cmp2);
  for (int i = 1; i < n; i++) {
    q.push_back({a[i + 1].y - a[i].y, {a[i + 1].ind, a[i].ind}});
  }
  sort(q.begin(), q.end());
  for (int i = 0; i < q.size(); i++) {
    int c = q[i].first, u = q[i].second.first, v = q[i].second.second;
    int uBatya = batya(u);
    int vBatya = batya(v);
    if (uBatya == vBatya) {
      continue;
    } else {
      if (rand() % 2 == 1) {
        p[uBatya] = vBatya;
      } else {
        p[vBatya] = uBatya;
      }
      ans += c;
    }
  }
  cout << ans;
  return 0;
}
