#include <bits/stdc++.h>
using namespace std;
const int INF = 1e9 + 7;
const int MOD = 1e9 + 7;
const int MAX_N = 300000;
int par[MAX_N];
int rnk[MAX_N];
void init(int n) {
  for (int i = 0; i < n; i++) {
    par[i] = i;
    rnk[i] = 0;
  }
}
int find(int x) {
  if (par[x] == x)
    return x;
  else
    par[x] = find(par[x]);
}
void unite(int x, int 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]++;
  }
}
bool same(int x, int y) { return find(x) == find(y); }
const int MAX_E = 300000;
struct edge {
  int u, v, cost;
};
bool comp(const edge& e1, const edge& e2) { return e1.cost < e2.cost; }
edge es[MAX_E];
int V, E;
int kruskal() {
  sort(es, es + E, comp);
  init(V);
  int res = 0;
  for (int i = 0; i < E; i++) {
    edge e = es[i];
    if (!same(e.u, e.v)) {
      unite(e.u, e.v);
      res += e.cost;
    }
  }
  return res;
}
int main() {
  vector<pair<int, int> > xv, yv;
  int n;
  cin >> n;
  for (int i = 0; i < n; i++) {
    int x, y;
    cin >> x >> y;
    xv.push_back(pair<int, int>(x, i));
    yv.push_back(pair<int, int>(y, i));
  }
  sort(xv.begin(), xv.end());
  sort(yv.begin(), yv.end());
  int k = 0;
  for (int i = 0; i < n - 1; i++) {
    es[k] = edge{xv[i].second, xv[i + 1].second,
                 min(abs(xv[i].first - xv[i + 1].first),
                     abs(yv[i].first - yv[i + 1].first))};
    k++;
    es[k] = edge{yv[i].second, yv[i + 1].second,
                 min(abs(xv[i].first - xv[i + 1].first),
                     abs(yv[i].first - yv[i + 1].first))};
    k++;
  }
  V = n;
  E = k;
  cout << kruskal() << endl;
}
