#include <bits/stdc++.h>
using namespace std;
struct DisjointSet {
  int sets;
  int* parent;
  int* members;
  void init(int n) {
    sets = n;
    parent = new int[n];
    members = new int[n];
    for (int i = 0; i < n; i++) {
      parent[i] = i;
      members[i] = 0;
    }
  }
  int find(int a) {
    if (a == parent[a]) return a;
    return parent[a] = find(parent[a]);
  }
  bool joined(int a, int b) { return find(a) == find(b); }
  void join(int a, int b) {
    if (joined(a, b)) return;
    members[find(b)] += members[find(a)];
    parent[find(a)] = find(b);
    sets--;
  }
};
int main() {
  DisjointSet ds;
  int n = 0, a = 0, b = 0, i = 0, idx = 0, idy = 0;
  long double d = 0;
  vector<pair<int, int> > vp;
  vector<pair<int, int> > x, y;
  scanf("%d", &n);
  ds.init(n + 1);
  for (i = 0; i < n; i++) {
    scanf("%d %d", &a, &b);
    vp.push_back(make_pair(a, b));
    x.push_back(make_pair(a, i));
    y.push_back(make_pair(b, i));
  }
  sort(x.begin(), x.end());
  sort(y.begin(), y.end());
  long long int res = 0;
  int aux = 0;
  for (i = 0; i < n; i++) {
    idx =
        lower_bound(x.begin(), x.end(), make_pair(vp[i].first, i)) - x.begin();
    idy =
        lower_bound(y.begin(), y.end(), make_pair(vp[i].second, i)) - y.begin();
    a = INT_MAX, aux = -1;
    if (idx - 1 >= 0)
      if (ds.joined(i, x[idx - 1].second) == 0) {
        a = min(abs(vp[i].first - x[idx - 1].first), a);
        if (a == abs(vp[i].first - x[idx - 1].first)) aux = 0;
      }
    if (idx + 1 < n)
      if (ds.joined(i, x[idx + 1].second) == 0) {
        a = min(abs(vp[i].first - x[idx + 1].first), a);
        if (a == abs(vp[i].first - x[idx + 1].first)) aux = 1;
      }
    if (idy - 1 >= 0)
      if (ds.joined(i, y[idy - 1].second) == 0) {
        a = min(abs(vp[i].second - y[idy - 1].first), a);
        if (a == abs(vp[i].second - y[idy - 1].first)) aux = 2;
      }
    if (idy + 1 < n)
      if (ds.joined(i, y[idy + 1].second) == 0) {
        a = min(abs(vp[i].second - y[idy + 1].first), a);
        if (a == abs(vp[i].second - y[idy + 1].first)) aux == 3;
      }
    if (aux == 0) {
      ds.join(i, x[idx - 1].second);
    } else if (aux == 1) {
      ds.join(i, x[idx + 1].second);
    } else if (aux == 2) {
      ds.join(i, y[idy - 1].second);
    } else if (aux == 3) {
      ds.join(i, y[idy + 1].second);
    }
    if (aux != -1) res += a;
  }
  printf("%lld\n", res);
  return 0;
}
