#include <bits/stdc++.h>
using namespace std;
struct point {
  long long x, y, id;
} p[100001];
struct edge_list {
  long long w, u, v;
  bool operator<(const edge_list &o) const { return w < o.w; }
};
long long n, ans = 0, up[100001];
vector<edge_list> edge;
long long union_find(long long u) {
  if (u == up[u]) {
    return u;
  }
  return union_find(up[u]);
}
void union_merge(long long u, long long v) {
  if (union_find(u) != union_find(v)) {
    up[union_find(u)] = union_find(v);
  }
}
signed main() {
  cin >> n;
  for (long long i = 1; i <= n; i++) {
    up[i] = i;
  }
  for (long long i = 1; i <= n; i++) {
    cin >> p[i].x >> p[i].y;
    p[i].id = i;
  }
  sort(p + 1, p + n + 1, [](point a, point b) { return a.x < b.x; });
  for (long long i = 1; i < n; i++) {
    edge.push_back({p[i + 1].x - p[i].x, p[i].id, p[i + 1].id});
  }
  sort(p + 1, p + n + 1, [](point a, point b) { return a.y < b.y; });
  for (long long i = 1; i < n; i++) {
    edge.push_back({p[i + 1].y - p[i].y, p[i].id, p[i + 1].id});
  }
  sort(edge.begin(), edge.end());
  for (auto x : edge) {
    long long u = x.u, v = x.v, w = x.w;
    if (union_find(u) != union_find(v)) {
      union_merge(u, v);
      ans += w;
    }
  }
  cout << ans << '\n';
}
