#include <bits/stdc++.h>
using namespace std;
int n, pa[100000];
struct A {
  int x, y, a;
};
struct B {
  int x, y, a;
};
A a[100000];
B b[100000];
bool operator<(A a, A b) { return a.x < b.x; }
bool operator<(B a, B b) { return a.y < b.y; }
int root(int x) {
  if (pa[x] == x) return x;
  return pa[x] = root(pa[x]);
}
struct C {
  int from, to, cost;
};
vector<C> c;
bool operator<(C a, C b) { return a.cost < b.cost; }
signed main() {
  cin >> n;
  for (int i = 0; i < n; i++) {
    pa[i] = i;
    a[i].a = i;
    b[i].a = i;
    cin >> a[i].x >> a[i].y;
    b[i].x = a[i].x, b[i].y = a[i].y;
  }
  sort(a, a + n);
  sort(b, b + n);
  for (int i = 0; i < n - 1; i++) {
    c.push_back(C{a[i].a, a[i + 1].a, abs(a[i].x - a[i + 1].x)});
    c.push_back(C{b[i].a, b[i + 1].a, abs(b[i].y - b[i + 1].y)});
  }
  sort(c.begin(), c.end());
  int ans = 0;
  for (int i = 0; c.size(); i++) {
    if (root(c[i].from) == root(c[i].to)) continue;
    ans += c[i].cost;
    pa[c[i].from] = pa[c[i].to];
  }
  cout << ans << endl;
  getchar();
  getchar();
}
