#include <bits/stdc++.h>
using namespace std;
const int inf = 2e9 + 7;
struct edge {
  int x, y, val;
  edge(int _x, int _y, int _val) { x = _x, y = _y, val = _val; }
};
vector<edge> v;
struct node {
  int x, y, num;
} dot1[100003], dot2[100003];
bool cmp1(node x, node y) { return x.x < y.x; }
bool cmp2(node x, node y) { return x.y < y.y; }
bool comp(edge x, edge y) { return x.val < y.val; }
int n, fa[100003], dis[100003], res;
bool vis[100003];
queue<int> q;
int find(int x) {
  if (fa[x] == x) return x;
  return fa[x] = find(fa[x]);
}
void merge(int x, int y) {
  int fx = find(x), fy = find(y);
  if (fx != fy) fa[x] = fy;
}
int main() {
  scanf("%d", &n);
  for (int i = 1; i <= n; i++) {
    scanf("%d%d", &dot1[i].x, &dot1[i].y);
    dot2[i].x = dot1[i].x;
    dot2[i].y = dot1[i].y;
    dot2[i].num = dot1[i].num = i;
  }
  sort(dot1 + 1, dot1 + n + 1, cmp1);
  sort(dot2 + 1, dot2 + n + 1, cmp2);
  for (int i = 2; i <= n; i++) {
    v.push_back(
        edge(dot1[i - 1].num, dot1[i].num, abs(dot1[i].x - dot1[i - 1].x)));
    v.push_back(
        edge(dot2[i - 1].num, dot2[i].num, abs(dot2[i].y - dot2[i - 1].y)));
  }
  sort(v.begin(), v.end(), comp);
  for (int i = 1; i <= n; i++) fa[i] = i;
  for (int i = 0; i < v.size(); i++) {
    if (find(v[i].x) != find(v[i].y)) {
      merge(v[i].x, v[i].y);
      res += v[i].val;
    }
  }
  printf("%d\n", res);
  return 0;
}
