#include <bits/stdc++.h>
using namespace tr1;
using namespace std;
inline bool feq(const double& a, const double& b) {
  return fabs(a - b) < 1e-10;
}
namespace std {
template <>
struct hash<pair<int, int>> {
  size_t operator()(const pair<int, int>& p) const {
    return hash<int>()(p.first) ^ hash<int>()(p.second);
  }
};
}  // namespace std
const int MAXN = 100100;
int N;
pair<int, int> pos[MAXN];
vector<int> edge[MAXN];
map<int, set<int>> xs, ys;
unordered_set<pair<int, int>> in;
int dist(int a, int b) {
  return min(abs(pos[a].first - pos[b].first),
             abs(pos[a].second - pos[b].second));
}
int main() {
  while (cin >> N) {
    xs.clear();
    ys.clear();
    for (int i = 0; i < N; ++i) {
      edge[i].clear();
      int x, y;
      cin >> x >> y;
      pos[i].first = x;
      pos[i].second = y;
      xs[x].insert(i);
      ys[y].insert(i);
    }
    for (int i = 0; i < N; ++i) {
      int x = pos[i].first;
      int y = pos[i].second;
      auto it = xs.upper_bound(x);
      if (it != xs.end()) {
        for (auto& v : it->second) edge[i].push_back(v);
      }
      -- --it;
      if (it != xs.end()) {
        for (auto& v : it->second) edge[i].push_back(v);
      }
      it = ys.upper_bound(y);
      if (it != ys.end()) {
        for (auto& v : it->second) edge[i].push_back(v);
      }
      -- --it;
      if (it != ys.end()) {
        for (auto& v : it->second) edge[i].push_back(v);
      }
    }
    long long res = 0;
    priority_queue<pair<int, int>, vector<pair<int, int>>,
                   greater<pair<int, int>>>
        que;
    in.insert(pos[0]);
    for (int i = 0; i < edge[0].size(); ++i) {
      int v = edge[0][i];
      que.push(pair<int, int>(dist(0, v), v));
    }
    while (!que.empty()) {
      pair<int, int> d_u = que.top();
      que.pop();
      int dis = d_u.first;
      int u = d_u.second;
      if (in.count(pos[u])) continue;
      in.insert(pos[u]);
      res += dis;
      for (int i = 0; i < edge[u].size(); ++i) {
        int v = edge[u][i];
        if (!in.count(pos[v])) que.push(pair<int, int>(dist(u, v), v));
      }
    }
    cout << res << endl;
  }
  return 0;
}
