#include <bits/stdc++.h>
using namespace std;
int n, x[100005], y[100005], ind[100005], p[100005];
int findSet(int u) { return p[u] == u ? u : (p[u] = findSet(p[u])); }
bool sameSet(int u, int v) { return findSet(u) == findSet(v); }
void unite(int u, int v) {
  if (((int)rand()) & 1) swap(u, v);
  p[findSet(u)] = findSet(v);
}
int main() {
  std::ios::sync_with_stdio(false);
  cin.tie(NULL);
  cin >> n;
  for (int i = 0, _i = (n); i < _i; ++i) {
    cin >> x[i] >> y[i];
    ind[i] = p[i] = i;
  }
  priority_queue<pair<int, pair<int, int> > > pq;
  sort(ind, ind + n, [&](int lhs, int rhs) { return x[lhs] <= x[rhs]; });
  for (int i = 0, _i = (n - 1); i < _i; ++i) {
    pq.push(
        make_pair(x[ind[i]] - x[ind[i + 1]], make_pair(ind[i], ind[i + 1])));
  }
  sort(ind, ind + n, [&](int lhs, int rhs) { return y[lhs] <= y[rhs]; });
  for (int i = 0, _i = (n - 1); i < _i; ++i) {
    pq.push(
        make_pair(y[ind[i]] - y[ind[i + 1]], make_pair(ind[i], ind[i + 1])));
  }
  long long ans = 0;
  while (!pq.empty()) {
    int curw = pq.top().first, u = pq.top().second.first,
        v = pq.top().second.second;
    pq.pop();
    if (sameSet(u, v)) continue;
    unite(u, v);
    ans += curw;
  }
  cout << -ans;
}
