#include <bits/stdc++.h>
using namespace std;
struct UF {
  int par[100005], rank[100005];
  void init(int n) {
    for (int i = 0; i < n; i++) {
      par[i] = i;
      rank[i] = 1;
    }
  }
  int find(int x) {
    if (x == par[x]) return x;
    return par[x] = find(par[x]);
  }
  void unite(int x, int y) {
    x = find(x);
    y = find(y);
    if (x == y) return;
    if (rank[x] < rank[y]) {
      par[x] = y;
    } else {
      par[y] = x;
      if (rank[x] == rank[y]) rank[x]++;
    }
  }
  bool same(int x, int y) { return find(x) == find(y); }
};
UF uf;
vector<pair<int, pair<int, int> > > edge;
pair<pair<int, int>, int> p1[100005];
pair<pair<int, int>, int> p2[100005];
int main() {
  int n;
  scanf("%d", &n);
  for (int i = 0; i < n; i++) {
    int a, b;
    scanf("%d %d", &a, &b);
    p1[i] = pair<pair<int, int>, int>(pair<int, int>(a, b), i);
    p2[i] = pair<pair<int, int>, int>(pair<int, int>(b, a), i);
  }
  sort(p1, p1 + n);
  sort(p2, p2 + n);
  for (int i = 0; i + 1 < n; i++) {
    pair<int, int> p = p1[i].first, q = p1[i + 1].first;
    int ct = min(abs(p.first - q.first), abs(p.second - q.second));
    edge.push_back(pair<int, pair<int, int> >(
        ct, pair<int, int>(p1[i].second, p1[i + 1].second)));
  }
  for (int i = 0; i + 1 < n; i++) {
    pair<int, int> p = p2[i].first, q = p2[i + 1].first;
    int ct = min(abs(p.first - q.first), abs(p.second - q.second));
    edge.push_back(pair<int, pair<int, int> >(
        ct, pair<int, int>(p2[i].second, p2[i + 1].second)));
  }
  sort(edge.begin(), edge.end());
  long long int ret = 0;
  uf.init(n + 2);
  for (int i = 0; i < n; i++) {
    pair<int, int> p = edge[i].second;
    if (!uf.same(p.first, p.second)) {
      uf.unite(p.first, p.second);
      ret += edge[i].first;
    }
  }
  printf("%lld\n", ret);
  return 0;
}
