#include <bits/stdc++.h>
using namespace std;
struct edge {
  long long u, v, cost;
};
bool comp(const edge& e1, const edge& e2) { return e1.cost < e2.cost; }
int par[1000001];
int find(int x) {
  if (par[x] == x) return x;
  return par[x] = find(par[x]);
}
bool same(int x, int y) { return find(x) == find(y); }
void unite(int x, int y) {
  x = find(x);
  y = find(y);
  if (x == y) return;
  par[x] = y;
}
int main(void) {
  vector<edge> es;
  int E, N;
  long long ans = 0;
  long long x[100001], y[100001];
  long long x2[100001], y2[100001];
  map<long long, long long> x_index;
  map<long long, long long> y_index;
  cin >> N;
  E = (N - 1) * 2;
  for (int i = 0; i < ((int)(N)); i++) {
    cin >> x[i] >> y[i];
    if (x_index.end() != x_index.find(x[i])) {
      unite(x_index[x[i]], i);
    }
    if (y_index.end() != y_index.find(y[i])) {
      unite(y_index[y[i]], i);
    }
    x_index[x[i]] = i;
    y_index[y[i]] = i;
    x2[i] = x[i];
    y2[i] = y[i];
  }
  sort(x2, x2 + N);
  sort(y2, y2 + N);
  for (int i = 0; i < ((int)(N - 1)); i++) {
    es.push_back(
        (edge){x_index[x2[i]], x_index[x2[i + 1]], abs(x2[i] - x2[i + 1])});
    es.push_back(
        (edge){y_index[y2[i]], y_index[y2[i + 1]], abs(y2[i] - y2[i + 1])});
  }
  sort(es.begin(), es.end(), comp);
  for (int i = 0; i < ((int)(N)); i++) par[i] = i;
  for (int i = 0; i < ((int)(E)); i++) {
    edge e = es[i];
    if (!same(e.u, e.v)) {
      unite(e.u, e.v);
      ans += e.cost;
    }
  }
  cout << ans << endl;
  return 0;
}
