#include <bits/stdc++.h>
using namespace std;
vector<pair<int, int>> vertexs[200000];
int already[200000] = {};
int main() {
  int n;
  cin >> n;
  vector<tuple<long long, long long, long long>> wow, aa;
  for (long long i = 0; i < n; ++i) {
    int a, b;
    cin >> a >> b;
    wow.push_back(make_tuple(a, b, i));
    aa.push_back(make_tuple(b, a, i));
  }
  sort(wow.begin(), wow.end());
  long long ans = 0;
  for (int i = 0; i < n - 1; ++i) {
    vertexs[i].push_back(make_pair(i + 1, get<0>(wow[i + 1]) - get<0>(wow[i])));
    vertexs[i + 1].push_back(make_pair(i, get<0>(wow[i + 1]) - get<0>(wow[i])));
  }
  sort(aa.begin(), aa.end());
  for (int i = 0; i < n - 1; ++i) {
    vertexs[get<2>(aa[i])].push_back(
        make_pair(get<2>(aa[i + 1]), get<0>(aa[i + 1]) - get<0>(aa[i])));
    vertexs[get<2>(aa[i + 1])].push_back(
        make_pair(get<2>(aa[i]), get<0>(aa[i + 1]) - get<0>(aa[i])));
  }
  priority_queue<pair<int, int>, vector<pair<int, int>>,
                 greater<pair<int, int>>>
      tmp;
  tmp.push(make_pair(0, 0));
  while (tmp.empty() == false) {
    pair<int, int> now = tmp.top();
    tmp.pop();
    if (already[now.second] == false) {
      ans += now.first;
      already[now.second] = true;
      for (int i = 0; i < vertexs[now.second].size(); ++i) {
        if (already[vertexs[now.second][i].first] == false) {
          tmp.push(make_pair(vertexs[now.second][i].second,
                             vertexs[now.second][i].first));
        }
      }
    }
  }
  cout << ans << endl;
  return 0;
}
