#include <bits/stdc++.h>
using namespace std;
const int inf = 0x3f3f3f3f;
const long long INF = (1LL << 62) - 1;
const long long mod = 1e9 + 7;
const int N = 1e5 + 5;
vector<pair<int, int> > tx, ty;
int n, m, x[N], y[N];
int p[N];
const int maxm = 5e5 + 5;
struct edge {
  int u, v, cost;
  bool operator<(const edge& rhs) const { return cost < rhs.cost; }
} e[N];
int Find(int x) { return p[x] == x ? x : p[x] = Find(p[x]); }
long long kruskal(int n, int m) {
  long long ans = 0;
  sort(e, e + m);
  for (int i = 0; i < m; i++) {
    int u = e[i].u;
    int v = e[i].v;
    u = Find(u);
    v = Find(v);
    if (u != v) {
      ans += e[i].cost;
      p[v] = u;
    }
  }
  return ans;
}
void addedge(int u, int v) {
  e[m].u = u, e[m].v = v, e[m++].cost = min(abs(x[u] - x[v]), abs(y[u] - y[v]));
}
int main() {
  scanf("%d", &n);
  for (int i = 1; i <= n; i++) p[i] = i;
  for (int i = 1; i <= n; i++) {
    scanf("%d%d", &x[i], &y[i]);
    tx.push_back({x[i], i});
    ty.push_back({y[i], i});
  }
  sort(tx.begin(), tx.end());
  sort(ty.begin(), ty.end());
  for (int i = 1; i < n - 1; i++) {
    addedge(tx[i - 1].second, tx[i].second);
    addedge(tx[i].second, tx[i + 1].second);
    addedge(ty[i - 1].second, ty[i].second);
    addedge(ty[i].second, ty[i + 1].second);
  }
  printf("%lld\n", kruskal(n, m));
  return 0;
}
