#include <bits/stdc++.h>
using namespace std;
int px[100005], py[1000005], par[100005];
pair<int, int> sx[100005], sy[100005];
int FIND(int x) {
  if (par[x] == x)
    return x;
  else
    return par[x] = FIND(par[x]);
}
int UNION(int u, int v) {
  u = FIND(u);
  v = FIND(v);
  if (u == v) return 0;
  par[u] = v;
  return 1;
}
inline int dist(int x, int y) {
  return min(abs(px[x] - py[y]), abs(py[x] - py[y]));
}
int main() {
  int n;
  scanf("%d", &n);
  for (int i = 0; i < n; i++) {
    scanf("%d%d", &px[i], &py[i]);
    par[i] = i;
    sx[i] = make_pair(px[i], i);
    sy[i] = make_pair(py[i], i);
  }
  sort(sx, sx + n);
  sort(sy, sy + n);
  set<pair<int, pair<int, int> > > st;
  for (int i = 0; i < n - 1; i++) {
    st.insert(make_pair(dist(sx[i].second, sx[i + 1].second),
                        make_pair(sx[i].second, sx[i + 1].second)));
    st.insert(make_pair(dist(sy[i].second, sy[i + 1].second),
                        make_pair(sy[i].second, sy[i + 1].second)));
  }
  long long res = 0;
  while ((int)st.size()) {
    auto cur = *(st.begin());
    st.erase(cur);
    int u = cur.second.first;
    int v = cur.second.second;
    res += (long long)UNION(u, v) * dist(u, v);
  }
  printf("%lld", res);
  return 0;
}
