#include <bits/stdc++.h>
using namespace std;
int main() {
  int n;
  map<int, vector<int> > first, second;
  scanf("%d", &n);
  pair<int, int> town[100005];
  for (int i = 0; i < n; i++) {
    int a, b;
    scanf("%d %d", &a, &b);
    first[a].push_back(i);
    second[b].push_back(i);
    town[i] = make_pair((a), (b));
  }
  long long ans = 0;
  priority_queue<pair<int, int>, vector<pair<int, int> >,
                 greater<pair<int, int> > >
      pq;
  pq.push(make_pair((0), (1)));
  int visit[100005];
  memset(visit, 0, sizeof(visit));
  while (!pq.empty()) {
    pair<int, int> p = pq.top();
    pq.pop();
    if (visit[p.second]) continue;
    visit[p.second] = 1;
    ans += p.first;
    int xx = town[p.second].first, yy = town[p.second].second;
    vector<int>::iterator it =
        lower_bound(first[xx].begin(), first[xx].end(), p.second);
    if (it == first[xx].begin()) {
      map<int, vector<int> >::iterator it2 = first.find(xx);
      if (it2 != first.begin()) {
        it2--;
        pq.push(make_pair((xx - it2->first), (it2->second.back())));
        it2++;
      }
    } else {
      it--;
      pq.push(make_pair((0), (*it)));
      it++;
    }
    it++;
    if (it == first[xx].end()) {
      map<int, vector<int> >::iterator it2 = first.upper_bound(xx);
      if (it2 != first.end()) {
        pq.push(make_pair((it2->first - xx), (it2->second.front())));
      }
    } else {
      pq.push(make_pair((0), (*it)));
    }
    it = lower_bound(second[yy].begin(), second[yy].end(), p.second);
    if (it == second[yy].begin()) {
      map<int, vector<int> >::iterator it2 = second.find(yy);
      if (it2 != second.begin()) {
        it2--;
        pq.push(make_pair((yy - it2->first), (it2->second.back())));
        it2++;
      }
    } else {
      it--;
      pq.push(make_pair((0), (*it)));
      it++;
    }
    it++;
    if (it == second[yy].end()) {
    } else {
      map<int, vector<int> >::iterator it2 = second.upper_bound(yy);
      if (it2 != second.end()) {
        pq.push(make_pair((it2->first - yy), (it2->second.front())));
      }
      pq.push(make_pair((0), (*it)));
    }
  }
  printf("%I64d\n", ans);
}
