#include <bits/stdc++.h>
using namespace std;
using ll = long long int;
int main() {
  int N;
  scanf("%d", &N);
  getchar();
  ;
  vector<pair<int, int>> V;
  V.reserve(N);
  for (int i = 0; i < N; ++i) {
    int xi;
    scanf("%d", &xi);
    getchar();
    ;
    int yi;
    scanf("%d", &yi);
    getchar();
    ;
    V.emplace_back(xi, yi);
  }
  auto dist = [&](int xn, int yn) {
    return min(abs(V[xn].first - V[yn].first),
               abs(V[xn].second - V[yn].second));
  };
  ll result = 0;
  multimap<int, int> xs;
  multimap<int, int> ys;
  for (int i = 0; i < N; ++i) {
    xs.emplace(V[i].first, i);
    ys.emplace(V[i].second, i);
  }
  auto remove_i = [&](int c) {
    auto xit = xs.equal_range(V[c].first).first;
    while (xit->second != c) ++xit;
    xs.erase(xit);
    auto yit = ys.equal_range(V[c].second).first;
    while (yit->second != c) ++yit;
    ys.erase(yit);
  };
  unordered_set<int> used;
  multimap<int, int> passes;
  passes.emplace(0, 0);
  while (used.size() < N) {
    int len = passes.begin()->first;
    int c = passes.begin()->second;
    passes.erase(passes.begin());
    if (!used.insert(c).second) continue;
    result += len;
    remove_i(c);
    {
      auto xu = xs.lower_bound(V[c].first);
      if (xu != xs.end()) passes.emplace(dist(xu->second, c), xu->second);
      auto xl = xs.upper_bound(V[c].first);
      if (xl != xs.begin()) --xl;
      if (xl != xs.end()) passes.emplace(dist(xl->second, c), xl->second);
      auto yu = ys.lower_bound(V[c].second);
      if (yu != ys.end()) passes.emplace(dist(yu->second, c), yu->second);
      auto yl = ys.upper_bound(V[c].second);
      if (yl != ys.begin()) --yl;
      if (yl != ys.end()) passes.emplace(dist(yl->second, c), yl->second);
    }
  }
  printf("%lld\n", result);
}
