#include <bits/stdc++.h>
using namespace std;
vector<pair<long long, pair<long long, long long> > > v;
int n;
vector<int> r, c;
long long a[100010][2];
int par[100010];
long long res = 0;
inline bool cmp1(int x, int y) { return a[x][0] < a[y][0]; }
inline bool cmp2(int x, int y) { return a[x][1] < a[y][1]; }
inline int pare(int x) {
  if (par[x] == x)
    return x;
  else
    return pare(par[x]);
}
void join(int x, int y) { par[pare(x)] = pare(y); }
int main() {
  scanf("%d", &n);
  for (int i = 0; i < n; i++) {
    r.push_back(i);
    c.push_back(i);
    scanf("%I64d%I64d", &a[i][0], &a[i][1]);
    par[i] = i;
  }
  sort(r.begin(), r.end(), cmp1);
  sort(c.begin(), c.end(), cmp2);
  for (int i = 1; i < n; i++) {
    v.push_back(
        make_pair(a[r[i]][0] - a[r[i - 1]][0], make_pair(r[i - 1], r[i])));
    v.push_back(
        make_pair(a[c[i]][1] - a[c[i - 1]][1], make_pair(c[i - 1], c[i])));
  }
  sort(v.begin(), v.end());
  for (int i = 0; i < v.size(); i++) {
    int x = v[i].second.first, y = v[i].second.second;
    int c = v[i].first;
    if (pare(x) != pare(y)) join(x, y), res += c;
  }
  printf("%I64d", res);
  return 0;
}
