#include <bits/stdc++.h>
using namespace std;
struct node {
  int x, y;
  long long val;
};
vector<int> p(100001, -1);
vector<int> d(100001, 0);
const bool operator<(const node &a, const node &b) { return (a.val > b.val); }
int dsu(int a) {
  if (p[a] == -1)
    return a;
  else
    return dsu(p[a]);
}
void dsu1(int a, int b) {
  if (p[a] != b) {
    int c = p[a];
    p[a] = b;
    dsu1(c, b);
  } else
    return;
}
int main() {
  priority_queue<node> qi;
  int n;
  cin >> n;
  vector<pair<long long, pair<long long, int> > > v1, v2;
  for (int i = 0; i < n; i++) {
    long long a, b;
    cin >> a >> b;
    v1.push_back(make_pair(a, make_pair(b, i)));
    v2.push_back(make_pair(b, make_pair(a, i)));
  }
  sort(v1.begin(), v1.end());
  sort(v2.begin(), v2.end());
  for (int i = 0; i < n - 1; i++) {
    node g;
    g.x = v1[i].second.second;
    g.y = v1[i + 1].second.second;
    g.val = v1[i + 1].first - v1[i].first;
    qi.push(g);
    g.x = v2[i].second.second;
    g.y = v2[i + 1].second.second;
    g.val = v2[i + 1].first - v2[i].first;
    qi.push(g);
  }
  long long brojac = 0;
  while (!qi.empty()) {
    node g;
    g = qi.top();
    qi.pop();
    int a = g.x;
    int b = g.y;
    long long c = g.val;
    a = dsu(a);
    b = dsu(b);
    if (a == b && a != -1)
      continue;
    else {
      if (d[a] > d[b]) {
        p[a] = b;
        int aa = g.x;
        dsu1(aa, b);
      } else if (d[a] < d[b]) {
        p[b] = a;
        int aa = g.y;
        dsu1(aa, a);
      } else {
        p[b] = a;
        d[a]++;
      }
      brojac += c;
    }
  }
  cout << brojac << endl;
  return 0;
}
