#include <bits/stdc++.h>
using namespace std;
map<int, set<int>> mp;
map<int, bool> vis;
const int oo = 1e9 + 1;
int main() {
  ios::sync_with_stdio(false);
  cin.tie(0);
  cout.precision(10);
  cout << fixed;
  int n;
  cin >> n;
  set<int> r, c;
  int cx, cy;
  for (int i = 0; i < n; i++) {
    int x, y;
    cin >> x >> y;
    r.insert(x);
    c.insert(y);
    y += oo;
    cx = x;
    cy = y;
    mp[x].insert(y);
    mp[y].insert(x);
  }
  priority_queue<pair<int, long long>> q;
  long long ans = 0;
  q.push({0, cx});
  q.push({0, cy});
  while (q.size()) {
    long long u = q.top().second;
    int cst = -q.top().first;
    q.pop();
    if (vis[u]) continue;
    long long add = 0;
    if (mp[u].empty())
      add += cst;
    else
      ans += cst;
    vis[u] = 1;
    if (u < oo) {
      r.erase(u);
      for (int i : mp[u]) {
        mp[i].erase(u);
        q.push({0, i});
        c.erase(i - oo);
      }
      mp[u].clear();
      auto it = r.lower_bound(u);
      if (it != r.end()) {
        q.push({-(*it - u + cst), *it});
      }
      if (it != r.begin()) {
        it--;
        q.push({-(-(*it) + u + cst), *it});
      }
    } else {
      c.erase(u - oo);
      for (int i : mp[u]) {
        mp[i].erase(u);
        q.push({0, i});
        r.erase(i);
      }
      mp[u].clear();
      u -= oo;
      auto it = c.lower_bound(u);
      if (it != c.end()) {
        q.push({-(*it - u + cst), *it + oo});
      }
      if (it != c.begin()) {
        it--;
        q.push({-(-(*it) + u + cst), *it + oo});
      }
    }
  }
  cout << ans << endl;
}
