#include <bits/stdc++.h>
using namespace std;
struct PT {
  int x, y, id;
  PT(int _x = 0, int _y = 0, int _id = -1) {
    x = _x;
    y = _y;
    id = _id;
  }
};
bool cmp1(PT a, PT b) { return make_pair(a.x, a.y) < make_pair(b.x, b.y); }
bool cmp2(PT a, PT b) { return make_pair(a.y, a.x) < make_pair(b.y, b.x); }
struct Edge {
  int u, v, w;
  Edge(int _u, int _v, int _w) {
    u = _u;
    v = _v;
    w = _w;
  }
};
bool cmp3(Edge a, Edge b) { return a.w < b.w; }
const int MAXN = 1e5 + 100;
vector<PT> data;
vector<Edge> edges;
int p[MAXN];
int getParent(int u) { return u == p[u] ? u : p[u] = getParent(p[u]); }
bool merged(int u, int v) {
  int pu = getParent(u);
  int pv = getParent(v);
  return pu == pv;
}
void merge(int u, int v) { p[u] = p[v]; }
int main() {
  int n;
  cin >> n;
  for (int i = 0; i < n; i++) {
    int x, y;
    cin >> x >> y;
    data.push_back(PT(x, y, i));
  }
  sort(data.begin(), data.end(), cmp1);
  for (int i = 1; i < data.size(); i++) {
    int u = data[i - 1].id;
    int v = data[i].id;
    edges.push_back(Edge(u, v, abs(data[i].x - data[i - 1].x)));
  }
  sort(data.begin(), data.end(), cmp2);
  for (int i = 1; i < data.size(); i++) {
    int u = data[i - 1].id;
    int v = data[i].id;
    edges.push_back(Edge(u, v, abs(data[i].y - data[i - 1].y)));
  }
  sort(edges.begin(), edges.end(), cmp3);
  for (int i = 0; i < n; i++) p[i] = i;
  long long cost = 0;
  for (int i = 0; i < edges.size(); i++) {
    if (merged(edges[i].u, edges[i].v)) continue;
    cost += edges[i].w;
    merge(edges[i].u, edges[i].v);
  }
  cout << cost << endl;
  return 0;
}
