#include <bits/stdc++.h>
using namespace std;
const long long INF = 20050208;
pair<long long, long long> sx[100005];
pair<long long, long long> sy[100005];
long long px[100005];
long long py[100005];
set<pair<long long, pair<long long, long long> > > st;
long long par[100005];
long long find(long long x) { return x == par[x] ? x : par[x] = find(par[x]); }
long long dis(long long a, long long b) {
  return min(abs(px[a] - px[b]), abs(py[a] - py[b]));
}
long long un(long long x, long long y) {
  long long a = find(x);
  long long b = find(y);
  if (a == b) {
    return 0;
  }
  par[x] = y;
  return 1;
}
int main() {
  long long n;
  cin >> n;
  for (long long i = 0; i < n; i++) {
    long long x, y;
    cin >> x >> y;
    par[i] = i;
    sx[i] = (make_pair(x, i));
    sy[i] = (make_pair(y, i));
    px[i] = x;
    py[i] = y;
  }
  sort(sx, sx + n);
  sort(sy, sy + n);
  for (long long i = 0; i < n - 1; i++) {
    st.insert(make_pair(dis(sx[i].second, sx[i + 1].second),
                        make_pair(sx[i].second, sx[i + 1].second)));
    st.insert(make_pair(dis(sy[i].second, sy[i + 1].second),
                        make_pair(sy[i].second, sy[i + 1].second)));
  }
  long long ans = 0;
  while (st.size()) {
    pair<long long, pair<long long, long long> > cur = *(st.begin());
    st.erase(cur);
    long long a = cur.second.first;
    long long b = cur.second.second;
    ans += un(a, b) * dis(a, b);
  }
  cout << ans;
  return 0;
}
