#include <bits/stdc++.h>
using namespace std;
int in() {
  int a;
  scanf("%d ", &a);
  return a;
}
struct City;
vector<City> cities;
struct City {
  int index;
  int x, y;
  int par;
  int root() {
    if (par == index) return par;
    return par = cities[par].root();
  }
  void merge(int i) { par = cities[i].root(); }
};
bool xcomp(const City &a, const City &b) { return a.x < b.x; }
bool ycomp(const City &a, const City &b) { return a.y < b.y; }
int main() {
  int N = in();
  cities.resize(N);
  for (int i = 0; i < (N); i++) {
    cities[i].index = cities[i].par = i;
    cities[i].x = in();
    cities[i].y = in();
  }
  vector<City> cx = cities, cy = cities;
  sort(cx.begin(), cx.end(), xcomp);
  sort(cy.begin(), cy.end(), ycomp);
  priority_queue<pair<int, pair<int, int> > > px, py;
  for (int i = 0; i < (N - 1); i++) {
    px.push(make_pair(cx[i].x - cx[i + 1].x,
                      make_pair(cx[i].index, cx[i + 1].index)));
    py.push(make_pair(cy[i].y - cy[i + 1].y,
                      make_pair(cy[i].index, cy[i + 1].index)));
  }
  long long ans = 0;
  int t = 0;
  while (t < N - 1) {
    int xdiff = px.empty() ? (1001001001) : -px.top().first;
    int ydiff = py.empty() ? (1001001001) : -py.top().first;
    if (xdiff < ydiff) {
      pair<int, pair<int, int> > top = px.top();
      px.pop();
      if (cities[top.second.first].root() != cities[top.second.second].root()) {
        cities[top.second.first].merge(top.second.second);
        ans += xdiff;
        t++;
      }
    } else {
      pair<int, pair<int, int> > top = py.top();
      py.pop();
      if (cities[top.second.first].root() != cities[top.second.second].root()) {
        cities[top.second.first].merge(top.second.second);
        ans += ydiff;
        t++;
      }
    }
  }
  cout << ans << endl;
  return 0;
}
