#include <bits/stdc++.h>
using namespace std;
int parent[100001], rankk[100001];
int n;
void set_parent() {
  for (auto i = 0; i <= (long long)(n); i++) parent[i] = i, rankk[i] = 0;
}
int find_parent(int p) {
  if (parent[p] == p)
    return p;
  else
    return parent[p] = find_parent(parent[p]);
}
void union_both(int a, int b) {
  if (rankk[a] > rankk[b]) swap(a, b);
  parent[a] = b;
  if (rankk[a] == rankk[b]) rankk[b]++;
}
int main() {
  ios_base::sync_with_stdio(0);
  cin.tie(0);
  cin >> n;
  vector<pair<int, int> > vec(n);
  vector<pair<int, int> > temp(n);
  int c = 0;
  map<pair<int, int>, int> mp;
  map<pair<int, int>, int> mp2;
  map<int, pair<int, int> > rev;
  for (auto i = 0; i < (long long)(n); i++) {
    cin >> vec[i].first >> vec[i].second;
    rev[c] = vec[i];
    mp2[temp[i]] = c;
    mp[vec[i]] = c++;
    temp[i] = {vec[i].second, vec[i].first};
  }
  sort(((vec).begin()), ((vec).end()));
  sort(((temp).begin()), ((temp).end()));
  vector<pair<int, pair<int, int> > > edges;
  long long sum = 0;
  for (auto i = 0; i < (long long)(n); i++) {
    int t = lower_bound(((vec).begin()), ((vec).end()), vec[i]) - vec.begin(),
        idx = mp[vec[i]];
    int c1 = abs(vec[t].first - vec[i].first), idx1 = mp[vec[t]];
    int t2 = lower_bound(((temp).begin()), ((temp).end()),
                         pair<int, int>(vec[i].second, vec[i].first)) -
             temp.begin();
    int c3 = abs(temp[t2].first - vec[i].second), idx3 = mp[temp[t2]];
    int mn1 = INT_MAX;
    for (int j = max(0, t - 20); j <= min(((int)((vec).size())), t + 20); j++) {
      int v = mp[vec[j]];
      if (j == t) continue;
      mn1 = min(mn1, abs(vec[i].first - vec[j].first));
    }
    for (int j = max(0, t - 20); j <= min(((int)((vec).size())), t + 20); j++) {
      if (mn1 == abs(vec[i].first - vec[j].first)) {
        int v = mp[vec[j]];
        edges.push_back({mn1, {idx, v}});
      }
    }
    mn1 = INT_MAX;
    for (int j = max(0, t2 - 20); j <= min(((int)((vec).size())), t2 + 20);
         j++) {
      int v = mp2[temp[j]];
      if (j == t2) continue;
      mn1 = min(mn1, abs(vec[i].second - temp[j].first));
    }
    for (int j = max(0, t2 - 20); j <= min(((int)((vec).size())), t2 + 20);
         j++) {
      if (mn1 == abs(vec[i].second - temp[j].first)) {
        int v = mp[temp[j]];
        edges.push_back({mn1, {idx, v}});
      }
    }
  }
  set_parent();
  sort(((edges).begin()), ((edges).end()));
  for (auto i = 0; i < (long long)(((int)((edges).size()))); i++) {
    int cost = edges[i].first, u = edges[i].second.first,
        v = edges[i].second.second;
    int a = find_parent(u), b = find_parent(v);
    if (a != b) {
      union_both(a, b);
      sum += cost;
    }
  }
  cout << sum;
  return 0;
}
