#include <bits/stdc++.h>
using namespace std;
const long double pi = 3.141592653589793;
int n, x, y;
set<pair<int, int>> se;
vector<pair<int, int>> vi;
vector<pair<int, int>> rvi;
map<pair<int, int>, int> ma;
vector<pair<long long, long long>> g[1 << 20];
vector<bool> visited(1 << 20, false);
bool comparator(const pair<int, int>& u, const pair<int, int>& v) {
  if (u.second < v.second) return true;
  return u.first < v.first;
}
int weight1(int i) {
  int x = vi[i].first - vi[i + 1].first;
  int y = vi[i].second - vi[i + 1].second;
  return min(abs(x), abs(y));
}
int weight2(int i) {
  int x = rvi[i].first - rvi[i + 1].first;
  int y = rvi[i].second - rvi[i + 1].second;
  return min(abs(x), abs(y));
}
int main() {
  std::ios::sync_with_stdio(false);
  cin >> n;
  for (int i = 0; i < n; i++) {
    cin >> x >> y;
    se.insert({x, y});
  }
  for (auto it = se.begin(); it != se.end(); it++) {
    vi.push_back(*it);
    rvi.push_back(*it);
  }
  sort(rvi.begin(), rvi.end(), comparator);
  for (int i = 0; i < vi.size(); i++) ma[vi[i]] = i + 1;
  for (int i = 0; i < vi.size() - 1; i++) {
    g[i + 1].push_back({weight1(i), i + 2});
    g[i + 2].push_back({weight1(i), i + 1});
    int x = ma[rvi[i]];
    int y = ma[rvi[i + 1]];
    g[x].push_back({weight2(i), y});
    g[y].push_back({weight2(i), x});
  }
  priority_queue<pair<int, int>, vector<pair<int, int>>,
                 greater<pair<int, int>>>
      pq;
  pq.push({0, 1});
  long long answer = 0;
  while (not pq.empty()) {
    pair<int, int> temp = pq.top();
    pq.pop();
    if (visited[temp.second]) continue;
    visited[temp.second] = 1;
    answer = answer + (long long)(temp.first);
    for (auto& z : g[temp.second]) {
      if (not visited[z.second]) {
        pq.push({z.first, z.second});
      }
    }
  }
  cout << answer << endl;
  return 0;
}
