#include <bits/stdc++.h>
using namespace std;
using namespace std;
long long powm(long long base, long long exp, long long mod = 1000000007) {
  long long ans = 1;
  while (exp) {
    if (exp & 1) ans = (ans * base) % mod;
    exp >>= 1, base = (base * base) % mod;
  }
  return ans;
}
multiset<pair<long long, long long>> second[2];
long long x[100005], y[100005];
vector<pair<pair<long long, long long>, long long>> edges;
struct DSU {
  long long sze[100005], arr[100005];
  void init() {
    for (long long i = 1; i < 100005; i++) arr[i] = i, sze[i] = 1;
  }
  void get_union(long long a, long long b) {
    long long root_a = root(a), root_b = root(b);
    if (sze[root_a] < sze[root_b])
      arr[root_a] = arr[root_b], sze[root_b] += sze[root_a];
    else
      arr[root_b] = arr[root_a], sze[root_a] += sze[root_b];
  }
  long long root(long long x) {
    while (arr[x] != x) arr[x] = arr[arr[x]], x = arr[x];
    return x;
  }
} dsu;
bool cmp(pair<pair<long long, long long>, long long> p,
         pair<pair<long long, long long>, long long> q) {
  return (p.second < q.second);
}
int main() {
  long long n, ans = 0;
  cin >> n;
  for (long long i = 1; i < n + 1; i++)
    cin >> x[i] >> y[i], second[0].insert({x[i], i}),
        second[1].insert({y[i], i});
  for (long long curr = 1; curr < n + 1; curr++) {
    second[0].erase(second[0].find({x[curr], curr}));
    second[1].erase(second[1].find({y[curr], curr}));
    long long chhota, bada;
    auto it = second[0].lower_bound(make_pair(x[curr], 0LL));
    if (it != second[0].begin()) {
      it--;
      pair<long long, long long> tmp = *it;
      chhota = tmp.first;
      edges.push_back(make_pair(make_pair(curr, tmp.second), x[curr] - chhota));
    }
    auto it1 = second[0].upper_bound(make_pair(x[curr], 1011111111));
    if (it1 != second[0].end()) {
      pair<long long, long long> tmp = *it1;
      bada = tmp.first;
      edges.push_back(make_pair(make_pair(curr, tmp.second), bada - x[curr]));
    }
    it = second[1].lower_bound(make_pair(y[curr], 0LL));
    if (it != second[1].begin()) {
      it--;
      pair<long long, long long> tmp = *it;
      chhota = tmp.first;
      edges.push_back(make_pair(make_pair(curr, tmp.second), y[curr] - chhota));
    }
    it1 = second[1].upper_bound(make_pair(y[curr], 1011111111));
    if (it1 != second[1].end()) {
      pair<long long, long long> tmp = *it1;
      bada = tmp.first;
      edges.push_back(make_pair(make_pair(curr, tmp.second), bada - y[curr]));
    }
    second[0].insert(make_pair(x[curr], curr));
    second[1].insert(make_pair(y[curr], curr));
  }
  dsu.init();
  sort((edges).begin(), (edges).end(), cmp);
  for (auto i : edges)
    if (dsu.root(i.first.first) != dsu.root(i.first.second))
      dsu.get_union(i.first.first, i.first.second), ans += i.second;
  cout << ans;
  return 0;
}
