#include <bits/stdc++.h>
using namespace std;
struct dsu {
  int djg[200007];
  int fa[200007];
  dsu() {
    for (int i = 0; i < 200007; i++) {
      djg[i] = 1;
      fa[i] = i;
    }
  }
  int root(int what) {
    if (fa[what] == what) return what;
    return fa[what] = root(fa[what]);
  }
  void conn(int a, int b) {
    fa[a] = b;
    djg[b]++;
  }
};
dsu bcj;
pair<int, pair<int, int> > ft[200007];
int n, nn;
pair<int, int> bb1[200007], bb2[200007];
int main() {
  scanf("%d", &n);
  for (int i = 0; i < n; i++) {
    int x, y;
    scanf("%d%d", &x, &y);
    bb1[i] = make_pair(x, i);
    bb2[i] = make_pair(y, i);
  }
  sort(bb1, bb1 + n);
  sort(bb2, bb2 + n);
  nn = 2 * n - 2;
  for (int i = 0; i < n - 1; i++)
    ft[i] = make_pair(abs(bb1[i + 1].first - bb1[i].first),
                      make_pair(bb1[i].second, bb1[i + 1].second));
  for (int i = 0; i < n - 1; i++)
    ft[i] = make_pair(abs(bb2[i + 1].first - bb2[i].first),
                      make_pair(bb2[i].second, bb2[i + 1].second));
  sort(ft, ft + nn);
  int sum = 0;
  for (int i = 0; i < nn; i++) {
    if (bcj.root(ft[i].second.first) == bcj.root(ft[i].second.second)) continue;
    sum += ft[i].first;
    bcj.conn(ft[i].second.first, ft[i].second.second);
  }
  printf("%d\n", sum);
  return 0;
}
