#include <bits/stdc++.h>
using namespace std;
pair<int, int> p[100005];
multiset<int> my;
int main() {
  int n;
  cin >> n;
  for (int i = 0; i < n; i++) {
    cin >> p[i].first >> p[i].second;
    my.insert(p[i].first);
    my.insert(p[i].second);
  }
  long long sum = 0;
  my.insert(-1);
  my.insert(1e9 + 1);
  set<int>::iterator it1;
  for (int i = 0; i < n; i++) {
    my.erase(my.find(p[i].first));
    my.erase(my.find(p[i].second));
    int mn = 1e9 + 8;
    it1 = my.upper_bound(p[i].first);
    if (*it1 != 1e9 + 1) mn = min(mn, abs(p[i].first - *it1));
    it1--;
    if (*it1 != -1) mn = min(mn, abs(p[i].first - *it1));
    it1 = my.upper_bound(p[i].second);
    if (*it1 != 1e9 + 1) mn = min(mn, abs(p[i].second - *it1));
    it1--;
    if (*it1 != -1) mn = min(mn, abs(p[i].second - *it1));
    if (mn == 1e9 + 8) mn = 0;
    sum += mn;
  }
  cout << sum << endl;
  return 0;
}
