#include <bits/stdc++.h>
using namespace std;
const int INF = 2e9;
struct pnt {
  int x, y;
  int id;
  void read(int i) {
    id = i;
    scanf("%d%d", &x, &y);
  }
  bool operator<(const pnt& p) const { return x < p.x; }
};
int n;
vector<pnt> ps;
bool read() {
  if (scanf("%d", &n) < 1) {
    return 0;
  }
  ps.resize(n);
  for (int i = 0; i < int(n); ++i) {
    ps[i].read(i);
  }
  return 1;
}
struct DSU {
  vector<int> par;
  DSU(int n = 0) { par.assign(n, -1); }
  int get(int x) { return par[x] < 0 ? x : par[x] = get(par[x]); }
  bool unite(int x, int y) {
    x = get(x);
    y = get(y);
    if (x == y) {
      return 0;
    }
    if (-par[x] < -par[y]) {
      swap(x, y);
    }
    par[x] += par[y];
    par[y] = x;
    return 1;
  }
};
map<int, vector<pair<int, int> > > ys;
vector<pair<int, int> > es;
map<int, pnt> by_id;
void build(int x1, int x2) {
  const auto& ys2 = ys[x2];
  for (const auto& cur : ys[x1]) {
    int y, id;
    tie(y, id) = cur;
    int pos =
        upper_bound(begin(ys2), end(ys2), make_pair(y, INF)) - ys2.begin();
    for (int it = 0; it < int(2); ++it) {
      if (0 <= pos && pos < ((int)(ys2).size())) {
        es.push_back(make_pair(id, ys2[pos].second));
      }
      --pos;
    }
  }
}
int dist(int i, int j) {
  const auto& p1 = by_id[i];
  const auto& p2 = by_id[j];
  return min(abs(p1.x - p2.x), abs(p1.y - p2.y));
}
int solve() {
  es.clear();
  by_id.clear();
  for (const auto& p : ps) {
    by_id[p.id] = p;
  }
  for (int it = 0; it < int(2); ++it) {
    sort(begin(ps), end(ps));
    ys.clear();
    for (int i = 0; i < int(((int)(ps).size())); ++i) {
      ys[ps[i].x].push_back(make_pair(ps[i].y, ps[i].id));
    }
    for (int i = 0; i < int(((int)(ps).size()) - 1); ++i) {
      if (ps[i].x != ps[i + 1].x) {
        build(ps[i].x, ps[i + 1].x);
      }
    }
    for (const auto& it : ys) {
      const auto& vect = it.second;
      for (int i = 0; i < int(((int)(vect).size()) - 1); ++i) {
        es.push_back(make_pair(vect[i].second, vect[i + 1].second));
      }
    }
    for (auto& p : ps) {
      swap(p.x, p.y);
    }
  }
  sort(begin(es), end(es),
       [&](const pair<int, int>& e1, const pair<int, int>& e2) {
         return dist(e1.first, e1.second) < dist(e2.first, e2.second);
       });
  int ans = 0;
  DSU dsu(((int)(ps).size()));
  for (const auto& e : es) {
    if (dsu.unite(e.first, e.second)) {
      const int d = dist(e.first, e.second);
      ans += d;
    }
  }
  return ans;
}
int main() {
  while (read()) {
    printf("%d\n", solve());
  }
  return 0;
}
