#include <bits/stdc++.h>
using namespace std;
vector<pair<pair<long long, long long>, long long>> p, q;
vector<pair<pair<long long, long long>, long long>> edj;
struct DSU {
  int n, x;
  vector<long long> p, r, sz;
  DSU(int N) {
    n = N;
    x = N - 1;
    sz.assign(N, 1);
    p.assign(N, 0);
    r.assign(N, 1);
    for (int i = 0; i < N; i++) p[i] = i;
  }
  int findset(int i) { return (p[i] == i) ? i : (p[i] = findset(p[i])); }
  bool issameset(int i, int j) { return findset(i) == findset(j); }
  void unionset(int i, int j) {
    int p1 = findset(i);
    int p2 = findset(j);
    if (p1 != p2) {
      x--;
      if (r[p1] >= r[p2]) {
        p[p2] = p1;
        sz[p1] += sz[p2];
        if (r[p1] == r[p2]) r[p1]++;
      } else {
        p[p1] = p2;
        sz[p2] += sz[p1];
      }
    }
  }
  void disp() {
    for (int i = 0; i < n; i++) cout << p[i] << ' ';
    cout << '\n';
  }
  int getsize(int i) { return sz[findset(i)]; }
  int noofdisjointsets() { return x; }
};
int main() {
  ios_base::sync_with_stdio(false);
  cin.tie(NULL);
  long long n, x, t, m, y, z;
  cin >> n;
  for (int i = 0; i < n; i++) {
    cin >> x >> y;
    p.push_back(make_pair(make_pair(x, y), i));
    q.push_back(make_pair(make_pair(y, x), i));
  }
  sort(p.begin(), p.end());
  sort(q.begin(), q.end());
  for (int i = 0; i < n - 1; i++) {
    edj.push_back(make_pair(
        make_pair(p[i + 1].first.first - p[i].first.first, p[i + 1].second),
        p[i].second));
    edj.push_back(make_pair(
        make_pair(q[i + 1].first.first - q[i].first.first, q[i + 1].second),
        q[i].second));
  }
  DSU foo(n);
  sort(edj.begin(), edj.end());
  long long cost = 0;
  for (int i = 0; (i < n) && (foo.noofdisjointsets()); i++) {
    x = edj[i].first.second;
    y = edj[i].second;
    if (!foo.issameset(x, y)) {
      foo.unionset(x, y);
      cost += edj[i].first.first;
    }
  }
  cout << cost;
  return 0;
}
