#include <bits/stdc++.h>
using namespace std;
map<pair<long long, long long>, long long> r;
map<pair<long long, long long>, pair<long long, long long> > p;
vector<pair<long long,
            pair<pair<long long, long long>, pair<long long, long long> > > >
    edge;
long long numset;
pair<long long, long long> a[100005];
void init(long long N) {
  numset = N;
  for (long long i = 0; i < N; i++) {
    p[a[i]] = a[i];
  }
}
pair<long long, long long> find(pair<long long, long long> i) {
  if (p[i].first == i.first && p[i].second == i.second)
    return p[i];
  else
    return find(p[i]);
}
bool same(pair<long long, long long> i, pair<long long, long long> j) {
  pair<long long, long long> u = find(i);
  pair<long long, long long> v = find(j);
  if (u.first == v.first && u.second == v.second) return 1;
  return 0;
}
void joint(pair<long long, long long> i, pair<long long, long long> j) {
  if (same(i, j) == 0) {
    numset--;
    r[find(j)] += r[find(i)];
    p[find(i)] = find(j);
  }
}
long long size(pair<long long, long long> i) { return r[find(i)]; }
long long kruskal(long long V) {
  sort(edge.begin(), edge.end());
  init(V);
  long long cost = 0;
  for (long long i = 0; i < edge.size(); i++) {
    pair<long long,
         pair<pair<long long, long long>, pair<long long, long long> > >
        front = edge[i];
    if (same(front.second.first, front.second.second) == 0) {
      cost += front.first;
      joint(front.second.first, front.second.second);
    }
  }
  return cost;
}
bool cmp(pair<long long, long long> a, pair<long long, long long> b) {
  return a.second < b.second;
}
signed main() {
  long long n;
  cin >> n;
  for (long long i = 1; i <= n; ++i) {
    long long x, y;
    cin >> x >> y;
    r[a[i]] = 1;
    a[i].first = x;
    a[i].second = y;
  }
  sort(a + 1, a + n + 1);
  for (long long i = 1; i < n; ++i) {
    for (long long j = i + 1; j <= i + 50 && j <= n; ++j) {
      edge.push_back(make_pair(a[j].first - a[i].first, make_pair(a[i], a[j])));
    }
  }
  sort(a + 1, a + n + 1, cmp);
  for (long long i = 1; i < n; ++i) {
    for (long long j = i + 1; j <= i + 50 && j <= n; ++j) {
      edge.push_back(
          make_pair(a[j].second - a[i].second, make_pair(a[i], a[j])));
    }
  }
  cout << kruskal(n);
}
