#include <bits/stdc++.h>
using namespace std;
struct edge {
  long long u, v, cost;
};
struct ver {
  long long x, y, num;
};
ver vv[100006];
ver vsave[100006];
edge es[300000];
long long V, E;
vector<long long> par;
vector<long long> rrank;
long long inx, iny;
void init_union_find(long long n) {
  par = vector<long long>(n);
  rrank = vector<long long>(n);
  for (long long(i) = (0); i < (n); (i)++) {
    par[i] = i;
    rrank[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 (rrank[x] < rrank[y]) {
    par[x] = y;
  } else {
    par[y] = x;
    if (rrank[x] == rrank[y]) rrank[x]++;
  }
}
bool same(long long x, long long y) { return find(x) == find(y); }
bool comp(const edge& e1, const edge& e2) { return e1.cost <= e2.cost; }
bool compx(const ver& e1, const ver& e2) { return e1.x <= e2.x; }
bool compy(const ver& e1, const ver& e2) { return e1.y <= e2.y; }
long long kruskal() {
  sort(es, es + E, comp);
  init_union_find(V);
  long long res = 0;
  for (long long(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;
}
long long p, q;
int main() {
  cin >> V;
  for (long long(i) = (0); i < (V); (i)++) {
    cin >> inx >> iny;
    ver vvv = {inx, iny, i};
    vv[i] = vvv;
    vsave[i] = vvv;
  }
  sort(vv, vv + V, compx);
  for (long long(i) = (0); i < (V - 1); (i)++) {
    p = vv[i].num;
    q = vv[i + 1].num;
    edge ee = {p, q,
               min(abs(vsave[p].x - vsave[q].x), abs(vsave[p].y - vsave[q].y))};
    es[E] = ee;
    E++;
  }
  sort(vv, vv + V, compy);
  for (long long(i) = (0); i < (V - 1); (i)++) {
    p = vv[i].num;
    q = vv[i + 1].num;
    edge ee = {p, q,
               min(abs(vsave[p].x - vsave[q].x), abs(vsave[p].y - vsave[q].y))};
    es[E] = ee;
    E++;
  }
  cout << kruskal() << endl;
  return 0;
}
