#include <bits/stdc++.h>
using namespace std;
long long dist(pair<long long, long long> p1, pair<long long, long long> p2) {
  return min(abs(p1.first - p2.first), abs(p1.second - p2.second));
}
long long p[100005];
void init(long long n) {
  for (long long i = 1; i <= n; i++) {
    p[i] = i;
  }
}
long long up(long long x) { return (p[x] == x ? x : up(p[x])); }
bool isSame(long long x, long long y) { return (up(x) == up(y)); }
void unionSet(long long x, long long y) {
  if (isSame(x, y)) return;
  p[up(y)] = up(x);
}
signed main() {
  long long n;
  scanf("%lld", &n);
  pair<pair<long long, long long>, long long> a[n + 1];
  for (long long i = 1; i <= n; i++) {
    long long x, y;
    scanf("%lld %lld", &a[i].first.first, &a[i].first.second);
    a[i].second = i;
  }
  init(n + 1);
  sort(a + 1, a + n + 1);
  priority_queue<pair<long long, pair<long long, long long> >,
                 vector<pair<long long, pair<long long, long long> > >,
                 greater<pair<long long, pair<long long, long long> > > >
      pq;
  for (long long i = 2; i <= n; i++)
    pq.push(make_pair(dist(a[i].first, a[i - 1].first),
                      make_pair(a[i].second, a[i - 1].second)));
  for (long long i = 1; i <= n; i++) swap(a[i].first.first, a[i].first.second);
  sort(a + 1, a + n + 1);
  for (long long i = 2; i <= n; i++)
    pq.push(make_pair(dist(a[i].first, a[i - 1].first),
                      make_pair(a[i].second, a[i - 1].second)));
  long long cur = n - 1;
  long long ans = 0;
  while (cur) {
    pair<long long, pair<long long, long long> > u = pq.top();
    pq.pop();
    if (isSame(u.second.first, u.second.second)) continue;
    unionSet(u.second.first, u.second.second);
    cur--;
    ans += u.first;
  }
  printf("%lld", ans);
  return 0;
}
