#include <bits/stdc++.h>

using namespace std;

typedef long long int llint;

const int N = 100303;
const llint inf = (llint) 1 << 40;

class UnionFind {
public:
  UnionFind(int n)
    :f(vector<int>(N))
  {
    for (int i = 0; i <= N; ++i) {
      f[i] = i;
    }
  }

  int find(int x) {
    if (f[x] != x) f[x] = find(f[x]);
    return f[x];
  }

  bool same(int x, int y) {
    return find(x) == find(y);
  }

  void unite(int x, int y) {
    f[x] = y;
  }

private:
  vector<int> f;
};

struct node {
  int id, val;
  bool operator<(const node& other) {
    return val < other.val;
  }
} a[N], b[N];

struct edge {
  int x, y, val;
  bool operator<(const edge& other) {
    return val < other.val;
  }
} c[N*2];

int main() {
  int n;
  cin >> n;
  for (int i = 1; i <= n; ++i) {
    int x, y;
    cin >> x >> y;
    a[i].id = i;
    a[i].val = x;
    b[i].id = i;
    b[i].val = y;
  }

  sort(a+1, a+n+1);
  sort(b+1, b+n+1);
  UnionFind uf(n);

  llint ans = 0;

  int t = 0;
  for (int i = 2; i <= n; ++i) {
    t++;
    c[t].x = a[i - 1].id;
    c[t].y = a[i].id;
    c[t].val = abs(a[i].val - a[i-1].val);
  }

  for (int i = 2; i <= n; ++i) {
    t++;
    c[t].x = b[i-1].id;
    c[t].y = b[i].id;
    c[t].val = abs(b[i].val - b[i-1].val);
  }

  sort(c+1, c+t+1);
  for (int i = 1; i <= t; ++i) {
    if (!uf.same(c[i].x, c[i].y)) {
      ans += c[i].val;
      uf.unite(c[i].x, c[i].y);
    }
  }

  cout << ans << endl;
  return 0;
}