#include <bits/stdc++.h>
using namespace std;
struct edge {
  long long from;
  long long to;
  long long cost;
  edge() {}
  edge(long long from, long long to, long long cost)
      : from(from), to(to), cost(cost) {}
  bool operator<(const edge& o) const { return o.cost < cost; }
};
struct UnionFind {
  vector<int> par;
  vector<int> sizes;
  UnionFind(int n) : par(n), sizes(n, 1) {
    for (int i = 0; i < int(n); i++) par[i] = i;
  }
  int find(int x) {
    if (x == par[x]) return x;
    return par[x] = find(par[x]);
  }
  void unite(int x, int y) {
    x = find(x);
    y = find(y);
    if (x == y) return;
    if (sizes[x] < sizes[y]) swap(x, y);
    par[y] = x;
    sizes[x] += sizes[y];
  }
  bool same(int x, int y) { return find(x) == find(y); }
  int size(int x) { return sizes[find(x)]; }
};
int main(void) {
  cin.tie(0);
  ios::sync_with_stdio(false);
  long long N;
  cin >> N;
  vector<pair<pair<long long, long long>, int>> P1(N);
  vector<pair<pair<long long, long long>, int>> P2(N);
  for (int i = 0; i < N; i++) {
    long long x, y;
    cin >> x >> y;
    P1[i] = {{x, y}, i};
    P2[i] = {{y, x}, i};
  }
  sort(P1.begin(), P1.end());
  sort(P2.begin(), P2.end());
  priority_queue<edge> pq;
  for (int i = 0; i < N - 1; i++) {
    long long cost1 = min(P1[i + 1].first.first - P1[i].first.first,
                          abs(P1[i + 1].first.second - P1[i].first.second));
    long long cost2 = min(P2[i + 1].first.first - P2[i].first.first,
                          abs(P2[i + 1].first.second - P2[i].first.second));
    pq.push(edge(P1[i].second, P1[i + 1].second, cost1));
    pq.push(edge(P2[i].second, P2[i + 1].second, cost2));
  }
  UnionFind uf(N);
  set<long long> used;
  long long ans = 0;
  while (!pq.empty()) {
    auto e = pq.top();
    pq.pop();
    if (uf.same(e.from, e.to)) continue;
    uf.unite(e.from, e.to);
    used.insert(e.from);
    used.insert(e.to);
    ans += e.cost;
    if (used.size() == N) break;
  }
  cout << ans << endl;
  return 0;
}
