#include <bits/stdc++.h>
using namespace std;
struct Edge {
  long long from;
  long long to;
  long long cost;
  Edge(long long from, long long to, long long cost)
      : from(from), to(to), cost(cost) {}
};
long long group_of(vector<long long>& union_find, long long idx) {
  long long i = idx;
  for (; union_find[i] != i; i = union_find[i])
    ;
  union_find[idx] = i;
  return i;
}
void unite(vector<long long>& union_find, long long from, long long to) {
  union_find[to] = from;
}
int main(void) {
  cin.tie(0);
  ios::sync_with_stdio(false);
  long long N;
  cin >> N;
  vector<long long> xidx(N), yidx(N), union_find(N);
  for (long long i = 0; i < N; i++) {
    xidx[i] = i;
    yidx[i] = i;
    union_find[i] = i;
  }
  vector<pair<long long, long long> > town(N);
  for (long long i = 0; i < N; i++) {
    long long x, y;
    cin >> x >> y;
    town[i] = pair<long long, long long>(x, y);
  }
  sort(xidx.begin(), xidx.end(), [town](long long left, long long right) {
    pair<long long, long long> l = town[left];
    pair<long long, long long> r = town[right];
    if (l.first < r.first) {
      return true;
    } else if (l.first == r.first) {
      return l.second < r.second;
    } else {
      return false;
    }
  });
  sort(yidx.begin(), yidx.end(), [town](long long left, long long right) {
    pair<long long, long long> l = town[left];
    pair<long long, long long> r = town[right];
    if (l.second < r.second) {
      return true;
    } else if (l.second == r.second) {
      return l.first < r.first;
    } else {
      return false;
    }
  });
  vector<Edge> E;
  for (long long i = 0; i < N - 1; i++) {
    long long d = town[xidx[i + 1]].first - town[xidx[i]].first;
    E.push_back(Edge(xidx[i], xidx[i + 1], d));
  }
  for (long long i = 0; i < N - 1; i++) {
    long long d = town[yidx[i + 1]].second - town[yidx[i]].second;
    E.push_back(Edge(yidx[i], yidx[i + 1], d));
  }
  sort(E.begin(), E.end(), [](Edge l, Edge r) { return l.cost < r.cost; });
  long long ans = 0;
  for (auto&& e : E) {
    long long from_group = group_of(union_find, e.from);
    long long to_group = group_of(union_find, e.to);
    if (from_group == to_group) {
      continue;
    }
    ans += e.cost;
    unite(union_find, from_group, to_group);
  }
  cout << ans << endl;
  return 0;
}
