#include <bits/stdc++.h>
const long long mod = 1e9 + 7;
using namespace std;
int main() {
  int n;
  cin >> n;
  multiset<pair<long long, long long>> ms, ms2;
  for (int i = 0; i < n; i++) {
    long long a, b;
    cin >> a >> b;
    ms.insert({a, b});
    ms2.insert({b, a});
  }
  long long cost = 0;
  pair<long long, long long> curr = *ms.begin();
  int ctr = 1;
  while (ctr < n) {
    if (ms.count(curr)) {
      ms.erase(ms.find(curr));
      ctr++;
      continue;
    }
    swap(curr.first, curr.second);
    if (ms2.count(curr)) {
      ms2.erase(ms2.find(curr));
      ctr++;
      continue;
    }
    long long c1 = 1e9;
    multiset<pair<long long, long long>>::iterator it =
        ms.lower_bound({curr.first, -1});
    if (it != ms.end()) {
      c1 = abs(curr.first - (*it).first);
    }
    multiset<pair<long long, long long>>::iterator temo = it;
    long long c2 = 1e9;
    it = ms2.lower_bound({curr.second, -1});
    if (it != ms2.end()) {
      c2 = abs(curr.second - (*it).second);
    }
    if (c1 < c2) {
      cost += c1;
      curr = (*temo);
      ms.erase(temo);
      ms2.erase({(*temo).first, (*temo).second});
      ctr++;
    } else {
      cost += c2;
      curr = (*it);
      ms2.erase(temo);
      ms.erase({(*temo).first, (*temo).second});
      ctr++;
    }
  }
  cout << cost;
  return 0;
}
