#include <bits/stdc++.h>
using namespace std;
int dx[4] = {1, 0, -1, 0};
int dy[4] = {0, 1, 0, -1};
struct UnionFind {
  long long size_;
  vector<long long> par;
  vector<long long> rank;
  vector<long long> sz;
  UnionFind(long long size_) : size_(size_) {
    par.resize(size_);
    rank.resize(size_);
    sz.resize(size_);
    for (long long i = 0; i < size_; i++) {
      par[i] = i;
      rank[i] = 0;
      sz[i] = 1;
    }
  }
  long long find(long long x) {
    return par[x] == x ? x : par[x] = find(par[x]);
  }
  void unite(long long x, long long y) {
    x = find(x);
    y = find(y);
    if (x == y) return;
    if (rank[y] < rank[x]) swap(x, y);
    if (rank[x] == rank[y]) rank[x]++;
    par[x] = y;
    sz[y] += sz[x];
  }
  bool same(long long x, long long y) { return find(x) == find(y); }
  long long size(long long x) { return sz[find(x)]; }
};
long long N;
using P = pair<long long, long long>;
vector<P> pos;
struct Edge {
  long long from, to, cost;
  Edge(long long from, long long to, long long cost)
      : from(from), to(to), cost(cost) {}
  bool operator<(const Edge &rhs) const { return cost < rhs.cost; }
};
vector<Edge> es;
map<P, long long> ids;
long long cost(P p1, P p2) {
  return min(abs(p1.first - p2.first), abs(p1.second - p2.second));
}
void add_edge(P p1, P p2) {
  long long a = ids[p1];
  long long b = ids[p2];
  long long c = cost(p1, p2);
  es.push_back(Edge(a, b, c));
  es.push_back(Edge(b, a, c));
}
void add() {
  sort((pos).begin(), (pos).end());
  for (long long i = 0; i < (long long)(N); i++)
    if (i) {
      add_edge(pos[i - 1], pos[i]);
      if (i + 1 < N) add_edge(pos[i], pos[i + 1]);
    }
  sort((pos).begin(), (pos).end(), [](const P &p1, const P &p2) {
    return P(p1.second, p1.first) < P(p2.second, p2.first);
  });
  for (long long i = 0; i < (long long)(N); i++)
    if (i) {
      add_edge(pos[i - 1], pos[i]);
      if (i + 1 < N) add_edge(pos[i], pos[i + 1]);
    }
}
signed main() {
  cin >> N;
  pos.resize(N);
  es.reserve(2 * N);
  for (long long i = 0; i < (long long)(N); i++)
    cin >> pos[i].first >> pos[i].second;
  for (long long i = 0; i < (long long)(N); i++) {
    long long n = ids.size();
    ids[pos[i]] = n;
  }
  add();
  sort((es).begin(), (es).end());
  UnionFind uf(N);
  long long ans = 0;
  for (auto e : es) {
    if (!uf.same(e.from, e.to)) {
      ans += e.cost;
      uf.unite(e.from, e.to);
    }
  }
  cout << ans << endl;
  return 0;
}
