#include <bits/stdc++.h>
using namespace std;
struct Edge {
  long long int to;
  long long int cost;
};
struct Node {
  long long int pos;
  long long int cost;
  bool operator<(const Node& r) const { return cost > r.cost; }
};
vector<long long int> x(1e5 + 5);
vector<long long int> y(1e5 + 5);
long long int dijkstra(vector<Edge>* g, long long int n) {
  long long int INF = pow(10, 10);
  vector<bool> visited(n, false);
  visited[0] = true;
  long long int sum = 0;
  long long int lx = x[0];
  long long int lxN = 0;
  long long int rx = x[0];
  long long int rxN = 0;
  long long int uy = y[0];
  long long int uyN = 0;
  long long int dy = y[0];
  long long int dyN = 0;
  long long int len = 1;
  while (len < n) {
    long long int next = 0;
    long long int cost = INF;
    set<long long int> v;
    v.insert(lxN);
    v.insert(rxN);
    v.insert(uyN);
    v.insert(dyN);
    for (auto src : v) {
      if (!visited[src]) continue;
      for (auto e : g[src]) {
        if (visited[e.to]) continue;
        if (e.cost < cost) {
          next = e.to;
          cost = e.cost;
        }
      }
    }
    len++;
    visited[next] = true;
    if (x[next] < lx) {
      lx = x[next];
      lxN = next;
    }
    if (rx < x[next]) {
      rx = x[next];
      rxN = next;
    }
    if (y[next] < dy) {
      dy = y[next];
      dyN = next;
    }
    if (uy < y[next]) {
      uy = y[next];
      uyN = next;
    }
    sum += cost;
  }
  return sum;
}
int main() {
  long long int n;
  cin >> n;
  for (long long int i = 0; i < (n); i++) cin >> x[i] >> y[i];
  vector<Edge> g[n];
  vector<Node> xs;
  for (long long int i = 0; i < (n); i++) xs.push_back({i, x[i]});
  sort(xs.begin(), xs.end());
  for (long long int i = 0; i < (n - 1); i++) {
    long long int cost = abs(xs[i].cost - xs[i + 1].cost);
    g[xs[i].pos].push_back({xs[i + 1].pos, cost});
    g[xs[i + 1].pos].push_back({xs[i].pos, cost});
  }
  vector<Node> ys;
  for (long long int i = 0; i < (n); i++) ys.push_back({i, y[i]});
  sort(ys.begin(), ys.end());
  for (long long int i = 0; i < (n - 1); i++) {
    long long int cost = abs(ys[i].cost - ys[i + 1].cost);
    g[ys[i].pos].push_back({ys[i + 1].pos, cost});
    g[ys[i + 1].pos].push_back({ys[i].pos, cost});
  }
  cout << dijkstra(g, n) << endl;
  return 0;
}
