#include <bits/stdc++.h>
using namespace std;
int n, ans;
pair<int, int> x[100005], y[100005];
int root[100005];
int cnt;
struct State {
  int x;
  int y;
  int w;
  State(int x, int y, int w) : x(x), y(y), w(w) {}
  bool operator<(const State& state) const { return w < state.w; }
};
set<State> st;
int find(int x) {
  if (root[x] != x) {
    root[x] = find(root[x]);
  }
  return root[x];
}
bool unite(int x, int y) {
  x = find(x), y = find(y);
  if (x == y) {
    return 0;
  }
  root[x] = y;
  return 1;
}
int main() {
  ios::sync_with_stdio(0), cin.tie(0), cout.tie(0);
  cin >> n;
  cnt = n;
  for (int i = 1; i <= n; i++) {
    root[i] = i;
    cin >> x[i].first >> y[i].first;
    x[i].second = y[i].second = i;
  }
  sort(x + 1, x + n + 1);
  sort(y + 1, y + n + 1);
  for (int i = n; i > 1; i--) {
    st.insert(State(x[i].second, x[i - 1].second, x[i].first - x[i - 1].first));
    st.insert(State(y[i].second, y[i - 1].second, y[i].first - y[i - 1].first));
  }
  for (__typeof(st.begin()) it = st.begin(); it != st.end(); it++) {
    State fr = *it;
    if (unite(fr.x, fr.y)) {
      ans += fr.w;
      cnt--;
      if (cnt == 1) {
        break;
      }
    }
  }
  cout << ans << '\n';
  return 0;
}
