#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> data;
  UnionFind(int size) : data(size, -1) {}
  bool unionSet(int x, int y) {
    x = root(x);
    y = root(y);
    if (x != y) {
      if (data[y] < data[x]) swap(x, y);
      data[x] += data[y];
      data[y] = x;
    }
    return x != y;
  }
  bool findSet(int x, int y) { return root(x) == root(y); }
  int root(int x) { return data[x] < 0 ? x : data[x] = root(data[x]); }
  int size(int x) { return -data[root(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.findSet(e.from, e.to)) continue;
    uf.unionSet(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;
}
