#include <bits/stdc++.h>
using namespace std;
const int N = 1e5 + 5;
long long dist[N];
vector<pair<long long, int>> node[N];
map<pair<int, int>, int> idx;
set<pair<long long, int>> st;
vector<pair<int, int>> vec;
int n, curr = 1;
long long dijkstra(int hoba) {
  st.insert({0, hoba});
  long long mx = 0;
  while (!st.empty()) {
    int a = (*st.begin()).second;
    long long cost = (*st.begin()).first;
    st.erase(st.begin());
    if (dist[a] != -1) continue;
    dist[a] = cost;
    for (auto i : node[a]) {
      if (dist[i.second] == -1) st.insert({cost + i.first, i.second});
    }
  }
  return mx;
}
int main() {
  ios_base::sync_with_stdio(0);
  cin.tie(0);
  cin >> n;
  vec.resize(n);
  for (auto i = 0; i < (long long)(n); i++) {
    int a, b;
    cin >> a >> b;
    if (!idx[{a, b}]) idx[{a, b}] = curr++;
    vec[i] = {a, b};
  }
  sort(((vec).begin()), ((vec).end()));
  for (auto i = 0; i < (long long)(n - 1); i++) {
    int a = idx[vec[i]], b = idx[vec[i + 1]];
    int val = min(abs(vec[i].first - vec[i + 1].first),
                  abs(vec[i].second - vec[i + 1].second));
    node[a].push_back({val, b});
    node[b].push_back({val, a});
  }
  for (auto i = 0; i < (long long)(n); i++) swap(vec[i].first, vec[i].second);
  sort(((vec).begin()), ((vec).end()));
  memset(dist, -1, sizeof dist);
  for (auto i = 0; i < (long long)(n - 1); i++) {
    int a = idx[{vec[i].second, vec[i].first}],
        b = idx[{vec[i + 1].second, vec[i + 1].first}];
    int val = min(abs(vec[i].first - vec[i + 1].first),
                  abs(vec[i].second - vec[i + 1].second));
    node[a].push_back({val, b});
    node[b].push_back({val, a});
  }
  long long sum = 0;
  for (auto i = 1; i < (long long)(curr); i++) {
    if (dist[i] == -1) sum += dijkstra(i);
  }
  vector<long long> vec;
  for (auto i = 1; i < (long long)(curr); i++) vec.push_back(dist[i]);
  sort(((vec).begin()), ((vec).end()));
  for (auto i = 0; i < (long long)(((int)((vec).size())) - 1); i++)
    sum += vec[i];
  cout << sum << '\n';
  return 0;
}
