#include <bits/stdc++.h>
using namespace std;
const long long inf = long long(1e9) + 7;
set<pair<int, int>> x, y;
int mk[111111];
pair<int, int> getMin(pair<int, int> p) {
  pair<int, int> ret(inf, inf);
  auto it = x.insert(pair<int, int>(p.first, -inf)).first;
  if (x.begin() != it) {
    auto it2 = it;
    it2--;
    ret = min(ret, pair<int, int>(abs(p.first - it2->first), it2->second));
  }
  auto sv = it;
  it++;
  if (x.end() != it) {
    ret = min(ret, pair<int, int>(abs(p.first - it->first), it->second));
  }
  x.erase(sv);
  it = y.insert(pair<int, int>(p.second, -inf)).first;
  if (y.begin() != it) {
    auto it2 = it;
    it2--;
    ret = min(ret, pair<int, int>(abs(p.second - it2->first), it2->second));
  }
  sv = it;
  it++;
  if (y.end() != it) {
    ret = min(ret, pair<int, int>(abs(p.second - it->first), it->second));
  }
  y.erase(sv);
  return ret;
}
pair<int, int> p[1111111];
int main() {
  ios::sync_with_stdio(0);
  int n;
  cin >> n;
  for (int i = 0, __ = n; i < __; i++) {
    int a, b;
    cin >> a >> b;
    if (i != 0) {
      x.insert(pair<int, int>(a, i));
      y.insert(pair<int, int>(b, i));
    }
    p[i] = pair<int, int>(a, b);
  }
  priority_queue<pair<pair<int, int>, int>, vector<pair<pair<int, int>, int>>,
                 greater<pair<pair<int, int>, int>>>
      pq;
  pq.push(pair<pair<int, int>, int>(getMin(p[0]), 0));
  mk[0] = 1;
  int ans = 0;
  for (int i = 1, __ = n; i < __; i++) {
    pair<pair<int, int>, int> tp = pq.top();
    pq.pop();
    if (mk[tp.first.second]) {
      pq.push(pair<pair<int, int>, int>(getMin(p[tp.second]), tp.second));
      i--;
      continue;
    }
    ans += tp.first.first;
    mk[tp.first.second] = 1;
    x.erase(pair<int, int>(p[tp.first.second].first, tp.first.second));
    y.erase(pair<int, int>(p[tp.first.second].second, tp.first.second));
    pq.push(pair<pair<int, int>, int>(getMin(p[tp.second]), tp.second));
    pq.push(
        pair<pair<int, int>, int>(getMin(p[tp.first.second]), tp.first.second));
  }
  cout << ans << endl;
  return 0;
}
