#include <bits/stdc++.h>
const long long mod = 1e9 + 7;
const long long INF = (long long)1e18;
using namespace std;
struct node {
  int x, y;
  int id;
  node(int x, int y, int id) : x(x), y(y), id(id) {}
};
int n;
int u[400200], v[400200], w[400200];
int r[400200], p[400200];
int lenu, lenv, lenw;
vector<node> s;
int cmp1(node a, node b) {
  if (a.x == b.x) return a.y < b.y;
  return a.x < b.x;
}
int cmp2(node a, node b) {
  if (a.y == b.y) return a.x < b.x;
  return a.y < b.y;
}
int cmp(int i, int j) { return w[i] < w[j]; }
int find(int x) { return x == p[x] ? x : find(p[x]); }
int kruskal() {
  int ans = 0;
  int m = lenu;
  for (int i = 0; i < n; i++) p[i] = i;
  for (int i = 0; i < m; i++) r[i] = i;
  sort(r, r + m, cmp);
  for (int i = 0; i < m; i++) {
    int e = r[i];
    int x = find(u[e]), y = find(v[e]);
    if (x != y) {
      ans += w[e];
      p[x] = y;
    }
  }
  return ans;
}
int main() {
  ios::sync_with_stdio(false);
  cin.tie(0), cout.tie(0);
  cin >> n;
  lenu = lenv = lenw = 0;
  for (int i = 1; i <= n; i++) {
    int x, y;
    cin >> x >> y;
    s.push_back(node(x, y, i));
  }
  sort(s.begin(), s.end(), cmp1);
  for (int i = 0; i < s.size() - 1; i++) {
    v[lenv++] = s[i].id;
    u[lenu++] = s[i + 1].id;
    w[lenw++] = min(abs(s[i + 1].x - s[i].x), abs(s[i + 1].y - s[i].y));
  }
  sort(s.begin(), s.end(), cmp2);
  for (int i = 0; i < s.size() - 1; i++) {
    v[lenv++] = s[i].id;
    u[lenu++] = s[i + 1].id;
    w[lenw++] = min(abs(s[i + 1].x - s[i].x), abs(s[i + 1].y - s[i].y));
  }
  cout << kruskal() << endl;
  return 0;
}
