#include <bits/stdc++.h>
using namespace std;
const long long mod = 1000000007;
const long long INF = 1e+14;
const long double eps = 1e-8;
const long double pi = acos(-1.0);
void Yes() {
  cout << "Yes" << endl;
  exit(0);
}
void No() {
  cout << "No" << endl;
  exit(0);
}
struct edge {
  int to;
  long long cost;
};
int N;
long long x[100100], y[100100];
long long mincost[100100];
vector<edge> G[100100];
int main() {
  ios::sync_with_stdio(false);
  cin.tie(0);
  cin >> N;
  map<long long, int> mpx, mpy;
  for (int i = 0; i < N; i++) {
    cin >> x[i] >> y[i];
    mpx[x[i]] = i;
    mpy[y[i]] = i;
  }
  sort(x, x + N);
  sort(y, y + N);
  for (int i = 0; i < N - 1; i++) {
    G[mpx[x[i]]].push_back(edge{mpx[x[i + 1]], abs(x[i] - x[i + 1])});
    G[mpx[x[i + 1]]].push_back(edge{mpx[x[i]], abs(x[i] - x[i + 1])});
    G[mpy[y[i]]].push_back(edge{mpy[y[i + 1]], abs(y[i] - y[i + 1])});
    G[mpy[y[i + 1]]].push_back(edge{mpy[y[i]], abs(y[i] - y[i + 1])});
  }
  priority_queue<pair<long long, long long>, vector<pair<long long, long long>>,
                 greater<pair<long long, long long>>>
      pque;
  fill(mincost, mincost + N, INF);
  mincost[0] = 0;
  pque.push(pair<long long, long long>(0, 0));
  long long ans = 0;
  while (pque.size()) {
    pair<long long, long long> p = pque.top();
    pque.pop();
    int v = p.second;
    if (mincost[v] < p.first) continue;
    ans += p.first;
    for (int i = 0; i < G[v].size(); i++) {
      edge e = G[v][i];
      if (mincost[e.to] > e.cost) {
        mincost[e.to] = e.cost;
        pque.push(pair<long long, long long>(mincost[e.to], e.to));
      }
    }
  }
  cout << ans << endl;
  return 0;
}
