#include <bits/stdc++.h>
using namespace std;
int find(vector<int> &parent, int cur) {
  if (cur == parent[cur])
    return cur;
  else
    return find(parent, parent[cur]);
}
void solve() {
  int n;
  cin >> n;
  vector<pair<int, int> > x_coord(n), y_coord(n);
  vector<pair<int, int> > vertexes(n);
  for (int i = 0; i < n; i++) {
    int x, y;
    cin >> x >> y;
    x_coord[i] = make_pair(x, i);
    y_coord[i] = make_pair(y, i);
    vertexes[i] = make_pair(x, y);
  }
  sort(x_coord.begin(), x_coord.end());
  sort(y_coord.begin(), y_coord.end());
  vector<pair<int, pair<int, int> > > edges;
  for (int i = 1; i < n; i++) {
    int u = x_coord[i - 1].second;
    int v = x_coord[i].second;
    int weight = x_coord[i].first - x_coord[i - 1].first;
    edges.push_back(make_pair(weight, make_pair(u, v)));
  }
  for (int i = 1; i < n; i++) {
    int u = y_coord[i - 1].second;
    int v = y_coord[i].second;
    int weight = y_coord[i].first - y_coord[i - 1].first;
    edges.push_back(make_pair(weight, make_pair(u, v)));
  }
  sort(edges.begin(), edges.end());
  vector<int> parent(n), rank(n);
  for (int i = 0; i < n; i++) parent[i] = i;
  int ans = 0;
  for (const auto &edge : edges) {
    int weight = edge.first;
    int u = edge.second.first;
    int v = edge.second.second;
    int up = find(parent, u);
    int vp = find(parent, v);
    if (up != vp) {
      parent[up] = vp;
      ans += weight;
    }
  }
  cout << ans;
}
int main() {
  ios_base::sync_with_stdio(0);
  cin.tie(0);
  solve();
}
