#include <bits/stdc++.h>
const int INF = 1e9;
const int MOD = 1e9 + 7;
const long long LINF = 1e18;
using namespace std;
void CINT() {}
template <class Head, class... Tail>
void CINT(Head&& head, Tail&&... tail) {
  cin >> head;
  CINT(move(tail)...);
}
class UnionFind {
 public:
  vector<int> par, rank;
  UnionFind(int n);
  int Find(int x);
  void Unite(int x, int y);
  bool Same(int x, int y);
};
UnionFind::UnionFind(int n) {
  par.resize(n);
  rank.resize(n);
  for (int i = 0; i < (n); ++i) {
    par[i] = i;
    rank[i] = 0;
  }
}
int UnionFind::Find(int x) { return (par[x] == x ? x : Find(par[x])); }
void UnionFind::Unite(int x, int y) {
  x = Find(x);
  y = Find(y);
  if (x == y) return;
  if (rank[x] < rank[y])
    par[x] = y;
  else {
    par[y] = x;
    if (rank[x] == rank[y]) rank[x]++;
  }
}
bool UnionFind::Same(int x, int y) { return (Find(x) == Find(y)); }
class Dijkstra {
 public:
  Dijkstra(vector<map<int, int>> ed, int firs, int pnum);
  void Solve();
  vector<int> range;
  vector<map<int, int>> edges;
  priority_queue<pair<int, int>, vector<pair<int, int>>,
                 greater<pair<int, int>>>
      que;
  vector<int> keiro;
  vector<int> CalcRoute(int startp, int endp);
};
Dijkstra::Dijkstra(vector<map<int, int>> ed, int firs, int pnum) {
  edges = ed;
  vector<int> ttt(pnum, INF);
  range = ttt;
  range[firs] = 0;
  que.push(make_pair(0, firs));
  keiro = vector<int>(pnum);
  for (int i = 0; i < (pnum); ++i) keiro[i] = i;
}
int main() {
  int n;
  CINT(n);
  vector<pair<int, int>> a(n);
  vector<pair<int, int>> b(n);
  for (int i = 0; i < (n); ++i) {
    int x, y;
    CINT(x, y);
    a[i] = make_pair(x, i);
    b[i] = make_pair(y, i);
  }
  sort((a).begin(), (a).end());
  sort((b).begin(), (b).end());
  int cost = 0;
  priority_queue<pair<int, pair<int, int>>, vector<pair<int, pair<int, int>>>,
                 greater<pair<int, pair<int, int>>>>
      que;
  for (int i = 0; i < (n - 1); ++i)
    que.push(make_pair(abs(a[i].first - a[i + 1].first),
                       make_pair(a[i].second, a[i + 1].second)));
  for (int i = 0; i < (n - 1); ++i)
    que.push(make_pair(abs(b[i].first - b[i + 1].first),
                       make_pair(b[i].second, b[i + 1].second)));
  UnionFind uni(n);
  while (1) {
    bool flag = true;
    if (!uni.Same(que.top().second.first, que.top().second.second)) {
      uni.Unite(que.top().second.first, que.top().second.second);
      cost += que.top().first;
      for (int i = 0; i < (n); ++i)
        if (!uni.Same(0, i)) {
          flag = false;
          break;
        }
      if (flag) break;
    }
    que.pop();
  }
  cout << (cost) << endl;
  return 0;
}
