#include <bits/stdc++.h>
using namespace std;
const int N = 200005;
const int inf = 2e9 + 7;
inline void read(int &x) {
  x = 0;
  char ch = getchar();
  while (ch < '0') ch = getchar();
  while (ch >= '0') {
    x = x * 10 + ch - 48;
    ch = getchar();
  }
}
pair<int, int> xjt[N], xjt2[N];
int b[N], a[N], id[N];
int fa[N];
inline int find(int x) { return x == fa[x] ? x : fa[x] = find(fa[x]); }
struct node {
  int type;
  int x;
  int cur;
  int d;
};
inline bool operator<(const node &x, const node &y) { return x.d > y.d; }
priority_queue<node> pq;
int main() {
  int n;
  scanf("%d", &n);
  for (int i = (1); i <= (n); i++) scanf("%d%d", &xjt[i].first, &xjt[i].second);
  sort(xjt + 1, xjt + 1 + n);
  for (int i = (1); i <= (n); i++)
    xjt2[i].first = xjt[i].second, xjt2[i].second = i;
  sort(xjt2 + 1, xjt2 + 1 + n);
  for (int i = (1); i <= (n); i++) {
    id[i] = xjt2[i].second;
    b[i] = xjt2[i].first;
    a[i] = xjt[i].first;
  }
  a[n + 1] = b[n + 1] = inf;
  for (int i = (1); i <= (n); i++) {
    node tt;
    tt.type = 0;
    tt.x = i;
    tt.cur = i + 1;
    tt.d = (a[i + 1] - a[i]);
    pq.push(tt);
    tt.type = 1;
    tt.x = i;
    tt.cur = i + 1;
    tt.d = (b[i + 1] - b[i]);
    pq.push(tt);
  }
  for (int i = (1); i <= (n); i++) fa[i] = i;
  int tot = n;
  long long ans = 0;
  while (tot > 1) {
    while (1) {
      node tt = pq.top();
      pq.pop();
      int x, y;
      long long quq = tt.d;
      if (tt.type) {
        x = id[tt.x];
        y = id[tt.cur];
      } else {
        x = tt.x;
        y = tt.cur;
      }
      x = find(x);
      y = find(y);
      tt.cur++;
      if (tt.type)
        tt.d = (b[tt.cur] - b[tt.x]);
      else
        tt.d = (a[tt.cur] - a[tt.x]);
      pq.push(tt);
      if (x == y) continue;
      fa[x] = y;
      ans += quq;
      break;
    }
    tot--;
  }
  printf("%lld\n", ans);
  return 0;
}
