#include <bits/stdc++.h>
using namespace std;
const int dr[] = {0, 0, -1, 1, -1, -1, 1, 1};
const int dc[] = {-1, 1, 0, 0, -1, 1, -1, 1};
int read() {
  int ret = 0, flag = 0;
  char ch;
  if ((ch = getchar()) == '-')
    flag = 1;
  else if (ch >= '0' && ch <= '9')
    ret = ch - '0';
  while ((ch = getchar()) >= '0' && ch <= '9') ret = ret * 10 + (ch - '0');
  return flag ? -ret : ret;
}
const int maxn = 100005;
long long dist[maxn];
bool vis[maxn];
int head[maxn];
int tot, n;
int fa[maxn];
struct node {
  int from, to;
  long long w;
  int next;
  bool operator<(const node& b) const { return w < b.w; }
} edge[maxn * 4];
struct Point {
  int id;
  int x, y;
} p[maxn];
void add(int u, int v, long long w) {
  edge[tot].from = u;
  edge[tot].to = v;
  edge[tot].w = w;
  edge[tot].next = head[u];
  head[u] = tot++;
}
int get(int x) {
  if (x == fa[x])
    return x;
  else
    return fa[x] = get(fa[x]);
}
bool cmp1(Point a, Point b) { return a.x < b.x; }
bool cmp2(Point a, Point b) { return a.y < b.y; }
int main() {
  memset(head, -1, sizeof(head));
  for (int i = 1; i <= n; i++) fa[i] = i;
  scanf("%d", &n);
  for (int i = 1; i <= n; i++) {
    scanf("%d%d", &p[i].x, &p[i].y);
    p[i].id = i;
  }
  sort(p + 1, p + n + 1, cmp1);
  for (int i = 2; i <= n; i++) {
    add(p[i - 1].id, p[i].id, p[i].x - p[i - 1].x);
  }
  sort(p + 1, p + n + 1, cmp2);
  for (int i = 2; i <= n; i++) {
    add(p[i - 1].id, p[i].id, p[i].y - p[i - 1].y);
  }
  sort(edge, edge + tot);
  int cnt = 0;
  long long ans = 0;
  for (int i = 0; i < tot; i++) {
    int fu = get(edge[i].from);
    int fv = get(edge[i].to);
    if (fu != fv) {
      fa[fu] = fv;
      cnt++;
      ans += edge[i].w;
      if (cnt == n - 1) break;
    }
  }
  printf("%lld\n", ans);
  return 0;
}
