#include <bits/stdc++.h>
using namespace std;
struct point {
  long long x, y, id;
} p[100010];
struct line {
  long long from, to, cost;
} l[1000010];
long long cnt, n, ans, fa[100010];
long long init(long long n) {
  for (long long i = 1; i <= n; i++) {
    fa[i] = i;
  }
}
long long find(long long x) {
  if (x == fa[x]) {
    return fa[x];
  }
  return fa[x] = find(fa[x]);
}
long long same(long long x, long long y) {
  long long fx = find(x);
  long long fy = find(y);
  if (fx == fy) {
    return 1;
  }
  return 0;
}
void union_(long long x, long long y) {
  long long fx = find(x);
  long long fy = find(y);
  if (fx == fy) {
    return;
  }
  fa[fx] = fy;
}
long long cmp1(point a, point b) { return a.x < b.x; }
long long cmp2(point a, point b) { return a.y < b.y; }
long long cmp3(line a, line b) { return a.cost < b.cost; }
signed main() {
  scanf("%lld", &n);
  for (long long i = 1; i <= n; i++) {
    scanf("%lld%lld", &p[i].x, &p[i].y);
    p[i].id = i;
  }
  sort(p + 1, p + n + 1, cmp1);
  for (long long i = 2; i <= n; i++) {
    l[++cnt].from = p[i].id;
    l[cnt].to = p[i - 1].id;
    l[cnt].cost = min(abs(p[i].x - p[i - 1].x), abs(p[i].y - p[i - 1].y));
    l[++cnt].to = p[i - 1].id;
    l[cnt].from = p[i].id;
    l[cnt].cost = min(abs(p[i].x - p[i - 1].x), abs(p[i].y - p[i - 1].y));
  }
  for (long long i = 1; i < n; i++) {
    l[++cnt].from = p[i].id;
    l[cnt].to = p[i + 1].id;
    l[cnt].cost = min(abs(p[i].x - p[i + 1].x), abs(p[i].y - p[i + 1].y));
    l[++cnt].to = p[i].id;
    l[cnt].from = p[i + 1].id;
    l[cnt].cost = min(abs(p[i].x - p[i + 1].x), abs(p[i].y - p[i + 1].y));
  }
  sort(p + 1, p + n + 1, cmp2);
  for (long long i = 2; i <= n; i++) {
    l[++cnt].from = p[i].id;
    l[cnt].to = p[i - 1].id;
    l[cnt].cost = min(abs(p[i].y - p[i - 1].y), abs(p[i].x - p[i - 1].x));
    l[++cnt].to = p[i].id;
    l[cnt].from = p[i - 1].id;
    l[cnt].cost = min(abs(p[i].y - p[i - 1].y), abs(p[i].x - p[i - 1].x));
  }
  for (long long i = 1; i < n; i++) {
    l[++cnt].from = p[i].id;
    l[cnt].to = p[i + 1].id;
    l[cnt].cost = min(abs(p[i].y - p[i + 1].y), abs(p[i].x - p[i + 1].x));
    l[++cnt].to = p[i].id;
    l[cnt].from = p[i + 1].id;
    l[cnt].cost = min(abs(p[i].y - p[i + 1].y), abs(p[i].x - p[i + 1].x));
  }
  sort(l + 1, l + cnt + 1, cmp3);
  init(cnt);
  for (long long i = 1; i <= cnt; i++) {
    if (same(l[i].from, l[i].to)) {
      continue;
    }
    ans += l[i].cost;
    union_(l[i].from, l[i].to);
  }
  printf("%lld\n", ans);
}
