#include <bits/stdc++.h>
using namespace std;
struct coor {
  int x, y;
};
struct point {
  int no;
  coor co;
};
struct edge {
  int u, v, w;
};
int n;
point p[100010];
edge edgeset[2 * 100010];
class disjoint_set {
 private:
  int pa[100010];
  int rnk[100010];

 public:
  void init(void) {
    memset(pa, 0, sizeof(pa));
    memset(rnk, 0, sizeof(rnk));
    for (int i = 0; i < n; i++) {
      pa[i] = i;
      rnk[i] = 0;
    }
  }
  int _find(int x) {
    if (pa[x] == x)
      return x;
    else
      return pa[x] = _find(pa[x]);
  }
  void unite(int x, int y) {
    x = _find(x);
    y = _find(y);
    if (x == y) return;
    if (rnk[x] < rnk[y])
      pa[x] = y;
    else {
      pa[y] = x;
      if (rnk[x] == rnk[y]) rnk[x]++;
    }
  }
  bool same(int x, int y) { return (_find(x) == _find(y)); }
};
int abs(int a) { return a >= 0 ? a : -a; }
bool cmp_x(point a, point b) {
  return a.co.x < b.co.x || a.co.x == b.co.x && a.co.y <= b.co.y;
}
bool cmp_y(point a, point b) {
  return a.co.y < b.co.y || a.co.y == b.co.y && a.co.x <= b.co.x;
}
bool cmp_edge(edge a, edge b) { return a.w <= b.w; }
int64_t mst(void) {
  disjoint_set ds;
  ds.init();
  int64_t res = 0;
  for (int i = 0; i < 2 * (n - 1); i++) {
    edge e = edgeset[i];
    if (!ds.same(e.u, e.v)) {
      ds.unite(e.u, e.v);
      res += (int64_t)e.w;
    }
  }
  return res;
}
int main(void) {
  scanf("%d", &n);
  for (int i = 0; i < n; i++) {
    scanf("%d%d", &p[i].co.x, &p[i].co.y);
    p[i].no = i;
  }
  sort(p, p + n, cmp_x);
  for (int i = 0; i < n - 1; i++) {
    edgeset[i].u = p[i].no;
    edgeset[i].v = p[i + 1].no;
    edgeset[i].w = abs(p[i + 1].co.x - p[i].co.x);
  }
  sort(p, p + n, cmp_y);
  for (int i = 0; i < n - 1; i++) {
    edgeset[i + n - 1].u = p[i].no;
    edgeset[i + n - 1].v = p[i + 1].no;
    edgeset[i + n - 1].w = abs(p[i + 1].co.y - p[i].co.y);
  }
  sort(edgeset, edgeset + 2 * (n - 1), cmp_edge);
  printf("%lld\n", mst());
  return 0;
}
