#include <bits/stdc++.h>
using namespace std;
int INF = 1e9 + 7;
int MOD = 998244353;
const long long N = 2e5 + 5;
const long long M = 1e6 + 5;
vector<int> dist, taken;
vector<vector<int> > adj;
vector<vector<pair<int, int> > > adj2;
priority_queue<pair<int, int>, vector<pair<int, int> >,
               greater<pair<int, int> > >
    pq;
void prim(int edge) {
  taken[edge] = 1;
  for (auto v : adj2[edge]) {
    if (taken[v.first] == 0) pq.push(pair<int, int>(v.second, v.first));
  }
}
int mst(int s) {
  taken.assign(N, 0);
  prim(s);
  int cost = 0;
  while (!pq.empty()) {
    pair<int, int> front = pq.top();
    pq.pop();
    int w = front.first;
    int u = front.second;
    if (taken[u] == 0) cost += w;
    prim(u);
  }
  return cost;
}
struct point {
  int x, y, idx;
};
bool cmp(point a, point b) { return a.x < b.x; }
bool cmp2(point a, point b) { return a.y < b.y; }
int main(void) {
  ios_base::sync_with_stdio(0);
  cin.tie(0);
  cout.tie(0);
  ;
  int n;
  cin >> n;
  point arr[n];
  for (int i = 0; i < n; i++) {
    cin >> arr[i].x >> arr[i].y;
    arr[i].idx = i;
  }
  sort(arr, arr + n, cmp);
  adj2.assign(n + 5, vector<pair<int, int> >());
  for (int i = 1; i < n; i++) {
    int a = arr[i].idx, b = arr[i - 1].idx;
    adj2[a].push_back(pair<int, int>(b, arr[i].x - arr[i - 1].x));
    adj2[b].push_back(pair<int, int>(a, arr[i].x - arr[i - 1].x));
  }
  sort(arr, arr + n, cmp2);
  for (int i = 1; i < n; i++) {
    int a = arr[i].idx, b = arr[i - 1].idx;
    adj2[a].push_back(pair<int, int>(b, arr[i].y - arr[i - 1].y));
    adj2[b].push_back(pair<int, int>(a, arr[i].y - arr[i - 1].y));
  }
  cout << mst(0) << "\n";
}
