#include <bits/stdc++.h>
using namespace std;
const long long INF = 1e9;
const long long MAX_N = 100010;
long long par[MAX_N];
long long myrank[MAX_N];
void init(long long n) {
  for (long long i = 0; i < n; i++) {
    par[i] = i;
    myrank[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 (myrank[x] < myrank[y]) {
    par[x] = y;
  } else {
    par[y] = x;
    if (myrank[x] == myrank[y]) myrank[x]++;
  }
}
bool same(long long x, long long y) { return find(x) == find(y); }
long long N;
long long X[100010], Y[100010];
pair<long long, long long> x[100010];
pair<long long, long long> y[100010];
struct edge {
  long long u, v, cost;
};
bool comp(const edge& e1, const edge& e2) { return e1.cost < e2.cost; }
edge es[200010];
signed main() {
  cin >> N;
  for (long long i = (0); i < (N); i++) {
    cin >> X[i];
    x[i].first = X[i];
    x[i].second = i;
    cin >> Y[i];
    y[i].first = Y[i];
    y[i].second = i;
  }
  sort(x, x + N);
  sort(y, y + N);
  init(N + 100);
  long long ans = 0;
  for (long long i = (0); i < (N); i++) {
    long long tempx = X[i], tempy = Y[i];
    long long xidx = lower_bound(x, x + N, make_pair(tempx, i)) - x;
    long long minidx, mincost = INT_MAX;
    if (xidx < N - 1) {
      if (x[xidx + 1].first - x[xidx].first < mincost) {
        minidx = x[xidx + 1].second;
        mincost = x[xidx + 1].first - x[xidx].first;
      }
    }
    if (0 < xidx) {
      if (x[xidx].first - x[xidx - 1].first < mincost) {
        minidx = x[xidx - 1].second;
        mincost = x[xidx].first - x[xidx - 1].first;
      }
    }
    edge e;
    e.cost = mincost;
    e.u = i;
    e.v = minidx;
    es[i] = e;
    long long mincost2 = INT_MAX, minidx2;
    long long yidx = lower_bound(y, y + N, make_pair(tempy, i)) - y;
    if (yidx < N - 1) {
      if (y[yidx + 1].first - y[yidx].first < mincost2) {
        minidx2 = y[yidx + 1].second;
        mincost2 = y[yidx + 1].first - y[yidx].first;
      }
    }
    if (0 < yidx) {
      if (y[yidx].first - y[yidx - 1].first < mincost2) {
        minidx2 = y[yidx - 1].second;
        mincost2 = y[yidx].first - y[yidx - 1].first;
      }
    }
    e.cost = mincost2;
    e.u = i;
    e.v = minidx2;
    es[N + i] = e;
  }
  sort(es, es + 2 * N, comp);
  long long res = 0;
  for (long long i = 0; i < 2 * N; i++) {
    edge e = es[i];
    if (!same(e.u, e.v)) {
      unite(e.u, e.v);
      res += e.cost;
    }
  }
  cout << res << endl;
}
