#include <bits/stdc++.h>
using namespace std;
using LL = long long;
using PII = pair<int, int>;
using VI = vector<int>;
template <typename T>
void _R(T &x) {
  cin >> x;
}
void _R(int &x) { scanf("%d", &x); }
void _R(LL &x) { scanf("%" PRId64, &x); }
void _R(double &x) { scanf("%lf", &x); }
void _R(char &x) { scanf(" %c", &x); }
void _R(char *x) { scanf("%s", x); }
void R() {}
template <typename T, typename... X>
void R(T &head, X &...tail) {
  _R(head);
  R(tail...);
}
const int MOD = 1e9 + 7;
const int N = 200005;
using TIIL = tuple<int, int, LL>;
int arr[N], par[N];
PII p[N];
vector<TIIL> edge;
LL dist(int a, int b) {
  return 1LL *
         min(abs(p[a].first - p[b].first), abs(p[a].second - p[b].second));
}
int find(int x) { return x == par[x] ? x : par[x] = find(par[x]); }
int main() {
  int n;
  R(n);
  for (int i = 0; i < n; i++) R(p[i].first, p[i].second);
  for (int i = 0; i < n; i++) arr[i] = par[i] = i;
  sort(arr, arr + n,
       [](const int &a, const int &b) { return p[a].first < p[b].first; });
  for (int i = 1; i < n; i++)
    edge.push_back({arr[i - 1], arr[i], dist(arr[i - 1], arr[i])});
  sort(arr, arr + n,
       [](const int &a, const int &b) { return p[a].second < p[b].second; });
  for (int i = 1; i < n; i++)
    edge.push_back({arr[i - 1], arr[i], dist(arr[i - 1], arr[i])});
  sort(edge.begin(), edge.end(),
       [](const TIIL &a, const TIIL &b) { return get<2>(a) < get<2>(b); });
  LL ans = 0;
  for (auto t : edge) {
    int a, b, c;
    tie(a, b, c) = t;
    if (find(a) == find(b)) continue;
    ans += c;
    par[find(a)] = find(b);
  }
  cout << ans << endl;
  return 0;
}
