#include <bits/stdc++.h>
using namespace std;
const int dx[] = {-1, 0, 1, 0};
const int dy[] = {0, -1, 0, 1};
int n, x[100010], y[100010], pa[100010];
pair<int, int> sx[100010], sy[100010];
int ans;
inline bool cmp(pair<int, int> x, pair<int, int> y) {
  return x.first < y.first;
}
inline int fnd(int x) { return (x == pa[x] ? x : fnd(pa[x])); }
int Onion(int x, int y) {
  x = fnd(x), y = fnd(y);
  if (x == y) return 0;
  pa[x] = y;
  return 1;
}
set<pair<int, pair<int, int> > > st;
int main(int argc, char const *argv[]) {
  ios::sync_with_stdio(false);
  cin >> n;
  for (int i = 0; i < n; i++) {
    cin >> x[i] >> y[i];
    pa[i] = i;
    sx[i] = make_pair(x[i], i), sy[i] = make_pair(y[i], i);
  }
  sort(sx, sx + n, cmp);
  sort(sy, sy + n, cmp);
  for (int i = 0; i < n - 1; i++) {
    st.insert(make_pair(min((abs(x[sx[i].second] - x[sx[i + 1].second])),
                            (abs(y[sx[i].second] - y[sx[i + 1].second]))),
                        make_pair(sx[i].second, sx[i + 1].second)));
    st.insert(make_pair(min((abs(x[sy[i].second] - x[sy[i + 1].second])),
                            (abs(y[sy[i].second] - y[sy[i + 1].second]))),
                        make_pair(sy[i].second, sy[i + 1].second)));
  }
  while (!st.empty()) {
    pair<int, pair<int, int> > cur = *(st.begin());
    st.erase(cur);
    int u = cur.second.first, v = cur.second.second;
    ans += (Onion(u, v) * (min((abs(x[u] - x[v])), (abs(y[u] - y[v])))));
  }
  cout << ans;
  return 0;
}
