#include <bits/stdc++.h>
using namespace std;
const int MAX = 1e5 + 5;
struct vertex {
  int ind, x, y;
};
bool cmp_x(const vertex &a, const vertex &b) { return a.x <= b.x; }
bool cmp_y(const vertex &a, const vertex &b) { return a.y <= b.y; }
vector<vertex> vx;
struct edge {
  int u, v, cost;
};
vector<edge> eg;
bool cmp_cost(const edge &a, const edge &b) { return a.cost <= b.cost; }
int par[MAX];
int rk[MAX];
void init(int n) {
  for (int i = 0; i < n; i++) {
    par[i] = i;
    rk[i] = 0;
  }
}
int find(int x) {
  if (par[x] == x) {
    return x;
  } else {
    return par[x] = find(par[x]);
  }
}
void unite(int x, int y) {
  x = find(x);
  y = find(y);
  if (x == y) return;
  if (rk[x] < rk[y]) {
    par[x] = y;
  } else {
    par[y] = x;
    if (rk[x] == rk[y]) rk[x]++;
  }
}
bool same(int x, int y) { return find(x) == find(y); }
int main() {
  int N;
  cin >> N;
  for (int(i) = 0; (i) < (N); (i)++) {
    int x, y;
    cin >> x >> y;
    vertex v = {i, x, y};
    vx.push_back(v);
  }
  sort(vx.begin(), vx.end(), cmp_x);
  for (int(i) = 0; (i) < (N - 1); (i)++) {
    edge e = {vx[i].ind, vx[i + 1].ind, abs(vx[i].x - vx[i + 1].x)};
    eg.push_back(e);
  }
  sort(vx.begin(), vx.end(), cmp_y);
  for (int(i) = 0; (i) < (N - 1); (i)++) {
    edge e = {vx[i].ind, vx[i + 1].ind, abs(vx[i].y - vx[i + 1].y)};
    eg.push_back(e);
  }
  sort(eg.begin(), eg.end(), cmp_cost);
  long long int ans = 0;
  init(N);
  for (int(i) = 0; (i) < (2 * N - 2); (i)++) {
    edge e = eg[i];
    if (!same(e.u, e.v)) {
      unite(e.u, e.v);
      ans = ans + (long long int)e.cost;
    }
  }
  cout << ans;
}
