#include <bits/stdc++.h>
using namespace std;
const int N = 100000 + 10;
const int M = 1000000007;
const double PI = atan(1) * 4;
const int oo = 1000000000;
int n, p[N];
vector<pair<int, int> > x, y;
vector<pair<int, pair<int, int> > > E;
int get(int u) {
  if (p[u] == u) return u;
  return p[u] = get(p[u]);
}
int main() {
  cin >> n;
  for (int a, b, i = 0; i < n; ++i) {
    scanf("%d%d", &a, &b);
    x.push_back(pair<int, int>(a, i));
    y.push_back(pair<int, int>(b, i));
    p[i] = i;
  }
  sort((x).begin(), (x).end());
  sort((y).begin(), (y).end());
  for (int i = 0; i < n - 1; ++i) {
    int c = x[i + 1].first - x[i].first;
    E.push_back(make_pair(c, pair<int, int>(x[i].second, x[i + 1].second)));
  }
  for (int i = 0; i < n - 1; ++i) {
    int c = y[i + 1].first - y[i].first;
    E.push_back(make_pair(c, pair<int, int>(y[i].second, y[i + 1].second)));
  }
  sort((E).begin(), (E).end());
  long long ans = 0;
  for (int i = 0; i < E.size(); ++i) {
    int c = E[i].first, a = E[i].second.first, b = E[i].second.second;
    if (get(a) != get(b)) {
      ans += c;
      p[get(a)] = get(b);
    }
  }
  cout << ans << endl;
}
