#include <bits/stdc++.h>
using namespace std;
const int MAX = 10010;
int n, x[MAX], y[MAX], par[MAX];
pair<int, int> sortx[MAX], sorty[MAX];
set<pair<int, pair<int, int> > > s;
long long ans;
int Find(int u) {
  if (par[u] != u)
    return par[u] = Find(par[u]);
  else
    return u;
}
int merge(int u, int v) {
  u = Find(u);
  v = Find(v);
  if (u == v)
    return 0;
  else {
    par[u] = v;
    return 1;
  }
}
int calc(int u, int v) { return min(abs(x[u] - x[v]), abs(y[u] - y[v])); }
int main() {
  cin >> n;
  for (int i = 0; i < n; i++) {
    cin >> x[i] >> y[i];
    sortx[i] = {x[i], i};
    sorty[i] = {y[i], i};
  }
  sort(sortx, sortx + n);
  sort(sorty, sorty + n);
  for (int i = 0; i < n; i++) {
    s.insert({calc(sortx[i].second, sortx[i + 1].second),
              {sortx[i].second, sortx[i + 1].second}}),
        s.insert({calc(sorty[i].second, sorty[i + 1].second),
                  {sorty[i].second, sorty[i + 1].second}});
  }
  while (!s.empty()) {
    pair<int, pair<int, int> > node = *(s.begin());
    s.erase(node);
    int v = node.second.first, u = node.second.second;
    ans += long long(merge(u, v) * calc(u, v));
  }
  cout << ans << endl;
  return 0;
}
