#include <bits/stdc++.h>
using namespace std;
int main() {
  int n;
  scanf("%d", &n);
  vector<tuple<int, int, int>> xy, yx;
  for (decltype(n) i = 0, _n = (n); i < _n; i++) {
    int x;
    scanf("%d", &x);
    int y;
    scanf("%d", &y);
    xy.push_back({x, y, i});
    yx.push_back({y, x, i});
  }
  sort(xy.begin(), xy.end());
  sort(yx.begin(), yx.end());
  map<int, vector<pair<int, int>>> gr;
  int u, v, c;
  for (decltype(n - 1) i = 0, _n = (n - 1); i < _n; i++) {
    u = get<2>(xy[i]);
    v = get<2>(xy[i + 1]);
    c = min(abs(get<0>(xy[i + 1]) - get<0>(xy[i])),
            abs(get<1>(xy[i + 1]) - get<1>(xy[i])));
    gr[u].push_back({-c, v});
    gr[v].push_back({-c, u});
    u = get<2>(yx[i]);
    v = get<2>(yx[i + 1]);
    c = min(abs(get<0>(yx[i + 1]) - get<0>(yx[i])),
            abs(get<1>(yx[i + 1]) - get<1>(yx[i])));
    gr[u].push_back({-c, v});
    gr[v].push_back({-c, u});
  }
  bool added[n + 1];
  memset(added, false, sizeof(added));
  long long ans = 0;
  priority_queue<pair<int, int>> pq;
  pq.push({0, 0});
  while (0 < int((pq).size())) {
    c = pq.top().first;
    u = pq.top().second;
    pq.pop();
    if (!added[u]) {
      added[u] = true;
      ans -= c;
      for (auto&& it = begin(gr[u]); it != end(gr[u]); it++) {
        pq.push(*it);
      }
    }
  }
  printf("%lld\n", ans);
  return 0;
}
