#include <bits/stdc++.h>
using namespace std;
char _buf[11 * 1000000 + 3];
int loadint() {
  if (fgets(_buf, 11 + 3, stdin) == NULL) return -1;
  return atoi(_buf);
}
int loadvec(vector<int>& v, int N) {
  int bufsize = 11 * N + 3;
  if (fgets(_buf, bufsize, stdin) == NULL) return -1;
  v.resize(N);
  int i = 0;
  bool last = false;
  for (char* p = &_buf[0];;) {
    char* q = p;
    while (*q > ' ') ++q;
    if (*q == 0x0D || *q == 0x0A) last = true;
    *q = 0;
    v[i++] = atoi(p);
    if (last || i == N) break;
    p = q + 1;
  }
  return i;
}
vector<bool> vis;
void jet(int v, vector<int>& x, vector<pair<int, int>>& xx,
         priority_queue<pair<int, pair<int, int>>>& pq, const char* x_y) {
  assert(vis[v]);
  int ix =
      (int)(lower_bound((xx).begin(), (xx).end(), pair<int, int>(x[v], v)) -
            xx.begin());
  assert(xx[ix].first == x[v]);
  assert(xx[ix].second == v);
  for (int i = ix - 1; i >= 0; --i) {
    int a = xx[i].second;
    if (!vis[a]) {
      pq.push(make_pair(-abs(x[a] - x[v]), pair<int, int>(v, a)));
      break;
    }
  }
  for (int i = ix + 1, c = xx.size(); i < c; ++i) {
    int a = xx[i].second;
    if (!vis[a]) {
      pq.push(make_pair(-abs(x[a] - x[v]), pair<int, int>(v, a)));
      break;
    }
  }
};
int get_nearest(priority_queue<pair<int, pair<int, int>>>& pq) {
  while (!pq.empty()) {
    int u = pq.top().second.first, v = pq.top().second.second;
    assert(vis[u]);
    if (vis[v]) {
      pq.pop();
      continue;
    } else {
      return -pq.top().first;
    }
  }
  return 0x7fffffff;
};
long long solve(int n, vector<int>& x, vector<int>& y) {
  assert(x.size() == n && y.size() == n);
  vis.assign(n, false);
  vector<pair<int, int>> xx(n), yy(n);
  for (int i = 0; i < (n); ++i) {
    xx[i] = pair<int, int>(x[i], i);
    yy[i] = pair<int, int>(y[i], i);
  }
  sort((xx).begin(), (xx).end());
  sort((yy).begin(), (yy).end());
  priority_queue<pair<int, pair<int, int>>> pqx, pqy;
  vis[0] = true;
  long long cost = 0;
  jet(0, x, xx, pqx, "x");
  jet(0, y, yy, pqy, "y");
  for (int z = 1; z < n; ++z) {
    int x_nearest = get_nearest(pqx);
    int y_nearest = get_nearest(pqy);
    if (x_nearest == 0x7fffffff && y_nearest == 0x7fffffff) {
      assert(false);
      break;
    }
    int v, a, d;
    if (x_nearest < y_nearest) {
      v = pqx.top().second.first;
      a = pqx.top().second.second;
      pqx.pop();
      d = x_nearest;
    } else {
      v = pqy.top().second.first;
      a = pqy.top().second.second;
      pqy.pop();
      d = y_nearest;
    }
    assert(vis[v] && !vis[a]);
    vis[a] = true;
    cost += d;
    jet(a, x, xx, pqx, "x");
    jet(a, y, yy, pqy, "y");
  }
  return cost;
}
int main() {
  int N = loadint();
  vector<int> tmp(2);
  vector<int> x(N), y(N);
  for (int i = 0; i < (N); ++i) {
    loadvec(tmp, 2);
    x[i] = tmp[0];
    y[i] = tmp[1];
  }
  printf("%lld\n", solve(N, x, y));
  return 0;
}
