#include <bits/stdc++.h>
using namespace std;
const int inf = 1000000001;
const long long INF = 1e16;
int dx[4] = {1, 0, -1, 0}, dy[4] = {0, 1, 0, -1};
int dx2[8] = {1, 1, 0, -1, -1, -1, 0, 1}, dy2[8] = {0, 1, 1, 1, 0, -1, -1, -1};
int n;
vector<vector<pair<int, int> > > M(100010, vector<pair<int, int> >());
vector<bool> used(100010, false);
vector<pair<pair<int, int>, int> > r(n);
vector<int> mincost(100010, inf);
bool cmp1(pair<pair<int, int>, int> a, pair<pair<int, int>, int> b) {
  if (a.first.second < b.first.second) {
    return true;
  } else if (a.first.second > b.first.second) {
    return false;
  } else {
    if (a.first.first < b.first.first) {
      return true;
    } else if (a.first.first > b.first.first) {
      return false;
    } else {
      if (a.second < b.second) {
        return true;
      } else {
        return false;
      }
    }
  }
}
void init() {
  cin >> n;
  for (int i = 0; i < n; i++) {
    cin >> r[i].first.first >> r[i].first.second;
    r[i].first.first--;
    r[i].first.second--;
    r[i].second = i;
  }
  sort(r.begin(), r.end());
  for (int i = 0; i < n - 1; i++) {
    int x1 = r[i].first.first, y1 = r[i].first.second;
    int x2 = r[i + 1].first.first, y2 = r[i + 1].first.second;
    int r1 = r[i].second, r2 = r[i + 1].second;
    M[r1].push_back(make_pair(min(abs(x2 - x1), abs(y2 - y1)), r2));
    M[r2].push_back(make_pair(min(abs(x2 - x1), abs(y2 - y1)), r1));
  }
  sort(r.begin(), r.end(), cmp1);
  for (int i = 0; i < n - 1; i++) {
    int x1 = r[i].first.first, y1 = r[i].first.second;
    int x2 = r[i + 1].first.first, y2 = r[i + 1].first.second;
    int r1 = r[i].second, r2 = r[i + 1].second;
    M[r1].push_back(make_pair(min(abs(x2 - x1), abs(y2 - y1)), r2));
    M[r2].push_back(make_pair(min(abs(x2 - x1), abs(y2 - y1)), r1));
  }
}
void prim(int s) {
  priority_queue<pair<int, int>, vector<pair<int, int> >,
                 greater<pair<int, int> > >
      pq;
  int used_cnt = 0;
  mincost[s] = 0;
  pq.push(make_pair(0, s));
  int i;
  while (used_cnt < n) {
    int u;
    pair<int, int> f;
    while (true) {
      f = pq.top();
      pq.pop();
      u = f.second;
      if (!used[u]) {
        break;
      }
    }
    mincost[u] = f.first;
    for (i = 0; i < M[u].size(); i++) {
      int v = M[u][i].second;
      int c = M[u][i].first;
      pq.push(make_pair(c, v));
    }
    used[u] = true;
    used_cnt++;
  }
}
void ans() {
  long long sum = 0;
  for (int i = 0; i < n; i++) {
    sum += mincost[i];
  }
  cout << sum << endl;
}
void solve() {
  init();
  prim(0);
  ans();
  return;
}
int main() { solve(); }
