#include <bits/stdc++.h>
const int INF = 1e9;
const int MOD = 1e9 + 7;
const long long LINF = 1e18;
using namespace std;
void CINT() {}
template <class Head, class... Tail>
void CINT(Head&& head, Tail&&... tail) {
  cin >> head;
  CINT(move(tail)...);
}
int main() {
  int n;
  CINT(n);
  vector<pair<int, int>> a(n);
  vector<pair<int, int>> b(n);
  for (int i = 0; i < (n); ++i) {
    int x, y;
    CINT(x, y);
    a[i] = make_pair(x, i);
    b[i] = make_pair(y, i);
  }
  sort((a).begin(), (a).end());
  sort((b).begin(), (b).end());
  int cost = 0;
  vector<map<int, int>> edges(n);
  for (int i = 0; i < (n - 1); ++i) {
    edges[a[i].second][a[i + 1].second] = abs(a[i].first - a[i + 1].first);
    edges[a[i + 1].second][a[i].second] = abs(a[i].first - a[i + 1].first);
  }
  for (int i = 0; i < (n - 1); ++i) {
    edges[b[i].second][b[i + 1].second] =
        (edges[b[i].second].count(b[i + 1].second)
             ? min(edges[b[i].second][b[i + 1].second],
                   abs(b[i].first - b[i + 1].first))
             : abs(b[i].first - b[i + 1].first));
    edges[b[i + 1].second][b[i].second] =
        (edges[b[i + 1].second].count(b[i].second)
             ? min(edges[b[i + 1].second][b[i].second],
                   abs(b[i].first - b[i + 1].first))
             : abs(b[i].first - b[i + 1].first));
  }
  set<int> set_ = {0};
  set<int> set__;
  for (int i = 0; i < (n); ++i) set__.insert(i);
  priority_queue<pair<int, int>, vector<pair<int, int>>,
                 greater<pair<int, int>>>
      que;
  for (auto&(xx) : (edges[0])) que.push(make_pair(xx.second, xx.first));
  while (!que.empty()) {
    int from = que.top().second;
    int cos = que.top().first;
    que.pop();
    if (set_.count(from)) continue;
    set_.insert(from);
    cost += cos;
    if (set_ == set__) break;
    for (auto&(xx) : (edges[from])) {
      int to = xx.first;
      int cost_ = xx.second;
      que.push(make_pair(cost_, to));
    }
  }
  cout << (cost) << endl;
  return 0;
}
