#include <bits/stdc++.h>
using namespace std;
template <typename T>
bool setmin(T& a, T b) {
  if (b < a) {
    a = b;
    return true;
  } else {
    return false;
  }
}
template <typename T>
bool setmax(T& a, T b) {
  if (b > a) {
    a = b;
    return true;
  } else {
    return false;
  }
}
template <typename T>
bool setmineq(T& a, T b) {
  if (b <= a) {
    a = b;
    return true;
  } else {
    return false;
  }
}
template <typename T>
bool setmaxeq(T& a, T b) {
  if (b >= a) {
    a = b;
    return true;
  } else {
    return false;
  }
}
template <typename T>
T gcd(T a, T b) {
  return (b == 0 ? a : gcd(b, a % b));
}
template <typename T>
T lcm(T a, T b) {
  return a / gcd(a, b) * b;
}
long long signed int n, x[100000], y[100000], ans;
pair<long long signed int, long long signed int> ppx[100000], ppy[100000];
array<long long signed int, 3> px[100000], py[100000];
const int N = 100001;
vector<int> v[N];
int id[N];
int unit, cn;
void init() {
  for (int i = (0); i < (n); i++) {
    v[i].push_back(i);
    id[i] = i;
  }
  unit = n;
  cn = n;
}
void unite(int xx, int yy) {
  int x = id[xx], y = id[yy];
  if (x == y) {
    return;
  }
  cn--;
  if (v[x].size() > v[y].size()) {
    swap(x, y);
  }
  if (v[x].size() == 1) {
    unit--;
  }
  if (v[y].size() == 1) {
    unit--;
  }
  for (int i = (v[x].size()) - 1; i >= (0); i--) {
    id[v[x][i]] = y;
    v[y].push_back(v[x][i]);
    v[x].pop_back();
  }
}
int main() {
  cin >> n;
  for (int i = (0); i < (n); i++) {
    cin >> x[i] >> y[i];
  }
  for (int i = (0); i < (n); i++) {
    ppx[i] = make_pair(x[i], i);
    ppy[i] = make_pair(y[i], i);
  }
  sort(ppx, ppx + n);
  sort(ppy, ppy + n);
  for (int i = (0); i < (n - 1); i++) {
    px[i] = {ppx[i + 1].first - ppx[i].first, ppx[i].second, ppx[i + 1].second};
    py[i] = {ppy[i + 1].first - ppy[i].first, ppy[i].second, ppy[i + 1].second};
  }
  sort(px, px + n - 1);
  sort(py, py + n - 1);
  init();
  int ix = 0, iy = 0;
  int test = 0;
  while (true) {
    test++;
    if (test > 30) {
      break;
    }
    if (ix == n - 1 && iy == n - 1) {
      break;
    }
    bool flag;
    if (iy == n - 1) {
      flag = true;
    } else if (ix == n - 1) {
      flag = false;
    } else {
      flag = (px[ix][0] <= py[iy][0]);
    }
    if (flag) {
      if (id[px[ix][1]] != id[px[ix][2]]) {
        unite(px[ix][1], px[ix][2]);
        ans += px[ix][0];
      }
      ix++;
    } else {
      if (id[py[iy][1]] != id[py[iy][2]]) {
        unite(py[iy][1], py[iy][2]);
        ans += py[iy][0];
      }
      iy++;
    }
  }
  cout << ans << endl;
  return 0;
}
