#include <bits/stdc++.h>
using namespace std;
long long mod(long long a) {
  long long c = a % 1000000007;
  if (c >= 0)
    return c;
  else
    return c + 1000000007;
}
int par[200005], dep[200005];
void init(int n) {
  for (int i = 0; i <= n - 1; i++) {
    par[i] = i;
    dep[i] = 0;
  }
}
int find(int x) { return par[x] == x ? x : par[x] = find(par[x]); }
void unite(int x, int y) {
  x = find(x);
  y = find(y);
  if (x == y) return;
  if (dep[x] < dep[y]) {
    par[x] = y;
  } else {
    par[y] = x;
    if (dep[x] == dep[y]) dep[x]++;
  }
}
bool same(int x, int y) { return find(x) == find(y); }
struct P {
  int num, x, y;
};
bool ascx(const P &l, const P &r) { return l.x <= r.x; }
bool ascy(const P &l, const P &r) { return l.y <= r.y; }
struct edge {
  int from, to, cost;
};
bool asce(const edge &l, const edge &r) { return l.cost <= r.cost; }
int main() {
  int n;
  cin >> n;
  P p[n];
  edge e[2 * n - 2];
  for (int i = 0; i <= n - 1; i++) {
    cin >> p[i].x >> p[i].y;
    p[i].num = i;
  }
  sort(p, p + n, ascx);
  for (int i = 1; i <= n - 1; i++) {
    e[i - 1] = edge{p[i - 1].num, p[i].num, abs(p[i].x - p[i - 1].x)};
  }
  sort(p, p + n, ascy);
  for (int i = 1; i <= n - 1; i++) {
    e[n + i - 2] = edge{p[i - 1].num, p[i].num, abs(p[i].y - p[i - 1].y)};
  }
  sort(e, e + 2 * n - 2, asce);
  init(n);
  long long ans = 0;
  for (auto x : e) {
    if (!same(x.from, x.to)) {
      ans += x.cost;
      unite(x.from, x.to);
    }
  }
  cout << ans << endl;
  return 0;
}
