#include <bits/stdc++.h>
using namespace std;
long long longinf = 1ll << 60;
int inf = 1 << 29;
int dx[4] = {1, -1, 0, 0};
int dy[4] = {0, 0, 1, -1};
int dh[4] = {0, 1, 0, -1};
int dw[4] = {1, 0, -1, 0};
pair<long long, long long> p[100001];
long long y[100001];
map<long long, long long> mp;
vector<pair<long long, long long>> v[100001];
int main() {
  int n;
  cin >> n;
  for (long long i = (long long)0ll; i < (long long)n; i++) {
    cin >> p[i].first >> p[i].second;
  }
  sort(p, p + n);
  for (long long i = (long long)0ll; i < (long long)n; i++) {
    long long y = p[i].second;
    mp[y] = i;
  }
  for (long long i = (long long)0ll; i < (long long)n; i++) {
    long long d;
    if (i != (n - 1)) {
      d = abs(p[i + 1].first - p[i].first);
      v[i].push_back({d, i + 1});
    }
    if (i != 0) {
      d = abs(p[i].first - p[i - 1].first);
      v[i].push_back({d, i - 1});
    }
  }
  long long y[100001];
  for (long long i = (long long)0ll; i < (long long)n; i++) {
    y[i] = p[i].second;
  }
  sort(y, y + n);
  map<long long, long long> mc;
  for (long long i = (long long)0ll; i < (long long)n; i++) {
    mc[y[i]] = i;
  }
  for (long long i = (long long)0ll; i < (long long)n; i++) {
    long long d;
    long long pp = p[i].second;
    long long in = mc[pp];
    if (in != (n - 1)) {
      d = abs(y[in + 1] - y[in]);
      long long k = mp[y[in + 1]];
      v[i].push_back({d, k});
    }
    if (in != 0) {
      d = abs(y[in] - y[in - 1]);
      long long k = mp[y[in - 1]];
      v[i].push_back({d, k});
    }
  }
  for (long long i = (long long)0ll; i < (long long)n; i++) {
    cout << i << "  ";
    for (long long j = (long long)0ll; j < (long long)v[i].size(); j++) {
      cout << v[i][j].first << " " << v[i][j].second << "  ";
    }
    cout << endl;
  }
  long long d[n];
  bool merged[n];
  for (long long i = (long long)0ll; i < (long long)n; i++) {
    merged[i] = false;
  }
  for (long long i = (long long)0ll; i < (long long)n; i++) d[i] = longinf;
  d[0] = 0;
  merged[0] = true;
  priority_queue<pair<long long, long long>, vector<pair<long long, long long>>,
                 greater<pair<long long, long long>>>
      q;
  q.push({0, 0});
  long long ans = 0;
  while (q.size()) {
    pair<long long, long long> hoge = q.top();
    q.pop();
    long long dist = hoge.first;
    long long node = hoge.second;
    if (merged[node]) continue;
    if (!merged[node]) ans += dist;
    merged[node] = true;
    for (long long i = (long long)0ll; i < (long long)v[node].size(); i++) {
      long long ndist = v[node][i].first;
      long long nnode = v[node][i].second;
      if (!merged[nnode]) {
        d[nnode] = min(ndist, d[nnode]);
        q.push({ndist, nnode});
      }
    }
  }
  cout << ans << endl;
  return 0;
}
