#include <bits/stdc++.h>
using namespace std;
struct Pair {
  long long x, y, id;
};
long long n;
Pair a[300000 + 1];
vector<pair<long long, long long> > G[300000 + 1];
bool cmp(Pair a, Pair b) { return a.x < b.x; };
bool CMP(Pair a, Pair b) { return a.y < b.y; };
bool visited[300000 + 1];
long long ans;
void DJK(long long x) {
  ans = 0;
  priority_queue<pair<long long, long long>,
                 vector<pair<long long, long long> >,
                 greater<pair<long long, long long> > >
      pq;
  pq.push({0, x});
  while (!pq.empty()) {
    long long u = pq.top().second;
    long long w = pq.top().first;
    pq.pop();
    if (visited[u]) continue;
    ans += w;
    visited[u] = 1;
    for (pair<long long, long long> ii : G[u]) {
      long long v = ii.second;
      pq.push({ii.first, v});
    }
  }
}
signed main() {
  cin >> n;
  for (long long i = 1; i <= n; i++) {
    cin >> a[i].x >> a[i].y;
    a[i].id = i;
  }
  sort(a + 1, a + n + 1, cmp);
  for (long long i = 2; i <= n; i++) {
    G[a[i].id].push_back({a[i].x - a[i - 1].x, a[i - 1].id});
    G[a[i - 1].id].push_back({a[i].x - a[i - 1].x, a[i].id});
  }
  sort(a + 1, a + n + 1, CMP);
  for (long long i = 2; i <= n; i++) {
    G[a[i].id].push_back({a[i].y - a[i - 1].y, a[i - 1].id});
    G[a[i - 1].id].push_back({a[i].y - a[i - 1].y, a[i].id});
  }
  DJK(1);
  cout << ans;
}
