#include <bits/stdc++.h>
using namespace std;
const int MAXN = 1e5 + 17;
const long long MOD = 1e9 + 7;
vector<pair<long long, long long> > G[MAXN];
map<pair<long long, long long>, long long> mp;
long long mincost[MAXN];
bool used[MAXN];
int V, m = 0;
long long prim() {
  V = m;
  long long res = 0;
  for (int i = 0; i < V; ++i) {
    mincost[i] = 9999999999999;
  }
  memset(used, 0, V * sizeof(bool));
  mincost[0] = 0;
  priority_queue<pair<long long, long long>,
                 vector<pair<long long, long long> >,
                 greater<pair<long long, long long> > >
      que;
  que.push(pair<long long, long long>(0, 0));
  while (!que.empty()) {
    pair<long long, long long> p = que.top();
    que.pop();
    long long v = p.second;
    if (used[v] || p.first > mincost[v]) continue;
    used[v] = true;
    res += 1LL * mincost[v];
    for (int i = 0; i < G[v].size(); ++i) {
      long long to = G[v][i].first, cost = G[v][i].second;
      if (mincost[to] > cost) {
        mincost[to] = cost;
        que.push(pair<long long, long long>(mincost[to], to));
      }
    }
  }
  assert(res > 0);
  return res;
}
int main(int argc, char const *argv[]) {
  int n;
  cin >> n;
  vector<pair<long long, long long> > x, y, all;
  for (int i = 0; i < n; ++i) {
    long long a, b;
    cin >> a >> b;
    if (mp[{a, b}] != 1) {
      mp[{a, b}] = 1;
      m++;
      all.push_back({a, b});
      x.push_back({a, i});
      y.push_back({b, i});
    }
  }
  sort(x.begin(), x.end());
  sort(y.begin(), y.end());
  for (int i = 0; i < m; ++i) {
    long long tx = all[i].first, ty = all[i].second;
    pair<long long, long long> tp = {tx, i};
    vector<pair<long long, long long> >::iterator itx1 =
        lower_bound(x.begin(), x.end(), tp);
    if ((itx1 + 1) != x.end() && (*(itx1 + 1)).first == tx) {
      itx1++;
    } else if (itx1 != x.begin())
      itx1--;
    long long cost = (tx - ((*itx1).first)), v = ((*itx1).second);
    G[i].push_back({v, cost});
    G[v].push_back({i, cost});
    itx1 = upper_bound(x.begin(), x.end(), tp);
    if (itx1 != x.end()) {
      cost = ((*itx1).first) - tx, v = ((*itx1).second);
      G[i].push_back({v, cost});
      G[v].push_back({i, cost});
    }
    tp = {ty, i};
    itx1 = lower_bound(y.begin(), y.end(), tp);
    if ((itx1 + 1) != y.end() && (((*(itx1 + 1)).first == ty))) {
      itx1++;
    } else if (itx1 != y.begin())
      itx1--;
    cost = ty - ((*itx1).first), v = ((*itx1).second);
    G[i].push_back({v, cost});
    G[v].push_back({i, cost});
    itx1 = upper_bound(y.begin(), y.end(), tp);
    if (itx1 != y.end()) {
      cost = ((*itx1).first) - ty, v = ((*itx1).second);
      G[i].push_back({v, cost});
      G[v].push_back({i, cost});
    }
  }
  cout << prim() << endl;
  return 0;
}
