#include <bits/stdc++.h>
using namespace std;
struct town {
  long long x;
  long long y;
  int id;
};
struct edge {
  long long cost;
  int src;
  int dst;
};
struct uf {
  int n;
  vector<int> p;
  uf(int n) : n(n), p(n) {
    for (int i = (int)(0); i < (int)(n); i++) {
      p[i] = i;
    }
  }
  int root(int x) {
    if (p[x] == x) return x;
    return p[x] = root(p[x]);
  }
  void unite(int x, int y) { p[x] = root(y); }
  bool find(int x, int y) { return root(x) == root(y); }
};
int main() {
  ios::sync_with_stdio(false);
  int N;
  cin >> N;
  vector<town> ts(N);
  for (auto &t : ts) {
    cin >> t.x >> t.y;
  }
  for (int i = (int)(0); i < (int)(N); i++) {
    ts[i].id = i;
  }
  vector<edge> es;
  sort(ts.begin(), ts.end(), [](town a, town b) { return a.x < b.x; });
  for (int i = (int)(0); i < (int)(N - 1); i++) {
    town a = ts[i];
    town b = ts[i + 1];
    es.push_back({b.x - a.x, a.id, b.id});
  }
  sort(ts.begin(), ts.end(), [](town a, town b) { return a.y < b.y; });
  for (int i = (int)(0); i < (int)(N - 1); i++) {
    town a = ts[i];
    town b = ts[i + 1];
    es.push_back({b.y - a.y, a.id, b.id});
  }
  sort(es.begin(), es.end(), [](edge a, edge b) { return a.cost < b.cost; });
  uf u(N);
  long long ans = 0;
  for (auto &e : es) {
    if (u.find(e.src, e.dst)) continue;
    ans += e.cost;
    u.unite(e.src, e.dst);
  }
  cout << ans << endl;
  return 0;
}
