#include <bits/stdc++.h>
using namespace std;
const long long MOD = 1000000007;
const long long INF = 1000000009;
const double PI = 3.141592653589;
struct Edge {
  long long src;
  long long dst;
  long long wei;
  Edge(long long s = 0, long long d = 0, long long w = 0)
      : src(s), dst(d), wei(w) {}
};
using Graph = vector<vector<Edge>>;
long long par[100005];
long long rnk[100005];
void init(long long n) {
  for (long long i = 0; i < n; i++) {
    par[i] = i;
    rnk[i] = 0;
  }
}
long long find(long long x) {
  if (par[x] == x)
    return x;
  else
    return par[x] = find(par[x]);
}
void unite(long long x, long long y) {
  x = find(x);
  y = find(y);
  if (x == y) return;
  if (rnk[x] < rnk[y])
    par[x] = y;
  else {
    par[y] = x;
    if (rnk[x] == rnk[y]) rnk[x]++;
  }
}
long long Kruskal(Graph& g) {
  vector<Edge> es;
  for (long long i = 0; i < g.size(); i++) {
    for (long long j = 0; j < g[i].size(); j++) {
      es.push_back(g[i][j]);
    }
  }
  sort(es.begin(), es.end(),
       [](const Edge& a, const Edge& b) { return a.wei < b.wei; });
  long long sum = 0;
  for (long long i = 0; i < es.size(); i++) {
    if (par[es[i].src] != par[es[i].dst]) {
      sum += es[i].wei;
      unite(es[i].src, es[i].dst);
    }
  }
  return sum;
}
signed main() {
  long long n;
  cin >> n;
  vector<pair<long long, long long>> vx(n), vy(n);
  long long x, y;
  for (long long i = 0; i < n; i++) {
    cin >> x >> y;
    vx[i] = make_pair(x, i);
    vy[i] = make_pair(y, i);
  }
  sort((vx).begin(), (vx).end());
  sort((vy).begin(), (vy).end());
  Graph g(n);
  for (long long i = 0; i < n - 1; i++) {
    long long sx = vx[i].second;
    long long dx = vx[i + 1].second;
    long long sy = vy[i].second;
    long long dy = vy[i + 1].second;
    g[sx].emplace_back(sx, dx, abs(vx[i].first - vx[i + 1].first));
    g[sy].emplace_back(sy, dy, abs(vy[i].first - vy[i + 1].first));
  }
  init(n);
  cout << Kruskal(g) << endl;
  return 0;
}
