#include <bits/stdc++.h>
using namespace std;
map<pair<int, int>, int> r;
map<pair<int, int>, pair<int, int> > p;
vector<pair<int, pair<pair<int, int>, pair<int, int> > > > edge;
int numset;
pair<int, int> a[100005];
void init(int N) {
  numset = N;
  for (int i = 0; i < N; i++) {
    p[a[i]] = a[i];
  }
}
pair<int, int> find(pair<int, int> i) {
  if (p[i].first == i.first && p[i].second == i.second)
    return p[i];
  else
    return find(p[i]);
}
bool same(pair<int, int> i, pair<int, int> j) {
  pair<int, int> u = find(i);
  pair<int, int> v = find(j);
  if (u.first == v.first && u.second == v.second) return 1;
  return 0;
}
void joint(pair<int, int> i, pair<int, int> j) {
  if (same(i, j) == 0) {
    numset--;
    r[find(j)] += r[find(i)];
    p[find(i)] = find(j);
  }
}
int size(pair<int, int> i) { return r[find(i)]; }
int kruskal(int V) {
  sort(edge.begin(), edge.end());
  init(V);
  int cost = 0;
  for (int i = 0; i < edge.size(); i++) {
    pair<int, pair<pair<int, int>, pair<int, int> > > front = edge[i];
    if (same(front.second.first, front.second.second) == 0) {
      cost += front.first;
      joint(front.second.first, front.second.second);
    }
  }
  return cost;
}
bool cmp(pair<int, int> a, pair<int, int> b) { return a.second < b.second; }
int main() {
  int n;
  cin >> n;
  for (int i = 1; i <= n; ++i) {
    int x, y;
    cin >> x >> y;
    r[a[i]] = 1;
    a[i].first = x;
    a[i].second = y;
  }
  sort(a + 1, a + n + 1);
  for (int i = 1; i < n; ++i)
    edge.push_back(
        make_pair(a[i + 1].first - a[i].first, make_pair(a[i], a[i + 1])));
  sort(a + 1, a + n + 1, cmp);
  for (int i = 1; i < n; ++i)
    edge.push_back(
        make_pair(a[i + 1].second - a[i].second, make_pair(a[i], a[i + 1])));
  cout << kruskal(n);
}
