#include <bits/stdc++.h>
using namespace std;
const long long MOD = 1e9 + 7;
typedef struct {
  long long u;
  long long v;
  long long cost;
} edge;
typedef struct {
  long long x;
  long long y;
  long long idx;
} edge2;
bool compx(edge2 l1, edge2 l2) { return l1.x < l2.x; }
bool compy(edge2 l1, edge2 l2) { return l1.y < l2.y; }
bool comp(edge l1, edge l2) { return l1.cost < l2.cost; }
long long parent[200010];
long long root(long long x) {
  if (x == parent[x])
    return x;
  else
    return parent[x] = root(parent[x]);
}
void unite(long long a, long long b) {
  a = root(a);
  b = root(b);
  if (a == b) return;
  parent[a] = b;
}
bool same(long long a, long long b) { return root(a) == root(b); }
int main() {
  cin.tie(0);
  ios::sync_with_stdio(false);
  long long N;
  long long x[100010], y[100010];
  cin >> N;
  for (int i = (0); i < (N); i++) cin >> x[i] >> y[i];
  vector<edge2> lp;
  for (int i = (0); i < (N); i++) {
    edge2 e = {x[i], y[i], i};
    lp.push_back(e);
  }
  sort(lp.begin(), lp.end(), compx);
  vector<edge> ee;
  for (int i = (1); i < (N - 1); i++) {
    edge tt = {lp[i - 1].idx, lp[i].idx, abs(lp[i - 1].x - lp[i].x)};
    ee.push_back(tt);
    edge tt2 = {lp[i + 1].idx, lp[i].idx, abs(lp[i + 1].x - lp[i].x)};
    ee.push_back(tt2);
  }
  sort(lp.begin(), lp.end(), compy);
  for (int i = (1); i < (N - 1); i++) {
    edge tt = {lp[i - 1].idx, lp[i].idx, abs(lp[i - 1].y - lp[i].y)};
    ee.push_back(tt);
    edge tt2 = {lp[i + 1].idx, lp[i].idx, abs(lp[i + 1].y - lp[i].y)};
    ee.push_back(tt2);
  }
  sort(ee.begin(), ee.end(), comp);
  for (int i = (0); i < (N); i++) parent[i] = i;
  long long ans = 0;
  for (auto &e : ee) {
    long long u = e.u;
    long long v = e.v;
    long long cost = e.cost;
    if (same(u, v)) continue;
    unite(u, v);
    ans += cost;
  }
  cout << (ans) << endl;
  ;
}
