#include <bits/stdc++.h>
using namespace std;
vector<pair<long long, pair<long long, long long>>> edge;
long long n, up[100005], sz[100005];
pair<pair<long long, long long>, long long> x[100005];
bool cmp(const pair<pair<long long, long long>, long long> &a,
         const pair<pair<long long, long long>, long long> &b) {
  return a.first.first < b.first.first;
}
bool cmp1(const pair<pair<long long, long long>, long long> &a,
          const pair<pair<long long, long long>, long long> &b) {
  return a.first.second < b.first.second;
}
int findSet(int x) {
  if (x == up[x])
    return x;
  else
    return findSet(up[x]);
}
void unionSet(int x, int y) {
  long long x1 = findSet(x), y1 = findSet(y);
  if (sz[x1] < sz[y1]) swap(x1, y1);
  up[y1] = x1;
  sz[x1] += sz[y1];
}
bool checkSet(int x, int y) {
  long long x1 = findSet(x), x2 = findSet(y);
  if (x1 == x2)
    return 1;
  else
    return 0;
}
int main() {
  cin.tie(0), cout.tie(0), ios::sync_with_stdio(0);
  cin >> n;
  for (int i = 1; i <= n; i++) {
    cin >> x[i].first.first >> x[i].first.second;
    x[i].second = i;
  }
  sort(x + 1, x + 1 + n, cmp);
  for (int i = 1; i <= n; i++) {
    up[i] = i;
    sz[i] = 1;
  }
  for (int i = 1; i < n; i++) {
    long long x1 = x[i].second, x2 = x[i + 1].second;
    long long val = abs(x[i].first.first - x[i + 1].first.first),
              val1 = abs(x[i].first.second - x[i + 1].first.second);
    edge.push_back(make_pair(min(val, LLONG_MAX), make_pair(x1, x2)));
  }
  sort(x + 1, x + 1 + n, cmp1);
  for (int i = 1; i < n; i++) {
    long long x1 = x[i].second, x2 = x[i + 1].second;
    long long val = abs(x[i].first.first - x[i + 1].first.first),
              val1 = abs(x[i].first.second - x[i + 1].first.second);
    edge.push_back(make_pair(min(val, LLONG_MAX), make_pair(x1, x2)));
  }
  long long sum = 0;
  sort(edge.begin(), edge.end());
  for (int i = 0; i < edge.size(); i++) {
    long long x1 = edge[i].second.first, x2 = edge[i].second.second;
    if (checkSet(x1, x2) == 0) {
      unionSet(x1, x2);
      sum += edge[i].first;
    }
  }
  cout << sum;
}
