#include <bits/stdc++.h>
using namespace std;
using pint = pair<int, int>;
using tint = tuple<int, int, int>;
template <class T>
inline bool chmax(T &a, T b) {
  if (a < b) {
    a = b;
    return 1;
  }
  return 0;
}
template <class T>
inline bool chmin(T &a, T b) {
  if (a > b) {
    a = b;
    return 1;
  }
  return 0;
}
constexpr double PI = 3.14159265358979323846;
constexpr int INF = INT_MAX / 2;
constexpr int64_t LINF = LLONG_MAX / 2;
struct UnionFind {
  vector<int> d;
  UnionFind(int n = 0) : d(n, -1) {}
  int find(int x) {
    if (d[x] < 0) return x;
    return d[x] = find(d[x]);
  }
  bool unite(int x, int y) {
    x = find(x);
    y = find(y);
    if (x == y) return false;
    if (d[x] > d[y]) swap(x, y);
    d[x] += d[y];
    d[y] = x;
    return true;
  }
  bool same(int x, int y) { return find(x) == find(y); }
  int size(int x) { return -d[find(x)]; }
};
template <typename T>
struct edge {
  int from, to;
  T cost;
};
template <typename T>
T kruskal(vector<edge<T>> &edges, int V) {
  sort(edges.begin(), edges.end(),
       [](const edge<T> &a, const edge<T> &b) { return a.cost < b.cost; });
  UnionFind unionFind(V);
  T res = 0;
  for (edge<T> &e : edges) {
    if (unionFind.unite(e.to, e.from)) {
      res += e.cost;
    }
  }
  return res;
}
int main() {
  int N;
  cin >> N;
  vector<tint> v, r;
  int a = 0, b = 0, c = 0, x, y, z;
  for (int i = 0; i < N; i++) {
    cin >> x >> y;
    v.push_back(make_tuple(x, y, i));
    r.push_back(make_tuple(y, x, i));
  }
  sort(v.begin(), v.end());
  sort(r.begin(), r.end());
  vector<edge<int64_t>> e(N * 2);
  for (int i = 0; i < N * 2 - 2; i++) {
    if (a == N - 1) {
      e.at(i).from = get<2>(r.at(b));
      e.at(i).to = get<2>(r.at(b + 1));
      e.at(i).cost = y;
      b++;
    } else if (b == N - 1) {
      e.at(i).from = get<2>(v.at(a));
      e.at(i).to = get<2>(v.at(a + 1));
      e.at(i).cost = x;
      a++;
    } else {
      x = get<0>(v.at(a + 1)) - get<0>(v.at(a));
      y = get<0>(r.at(b + 1)) - get<0>(r.at(b));
      if (x > y) {
        e.at(i).from = get<2>(r.at(b));
        e.at(i).to = get<2>(r.at(b + 1));
        e.at(i).cost = y;
        b++;
      } else {
        e.at(i).from = get<2>(v.at(a));
        e.at(i).to = get<2>(v.at(a + 1));
        e.at(i).cost = x;
        a++;
      }
    }
  }
  cout << kruskal(e, N) << '\n';
}
