#include <bits/stdc++.h>
using namespace std;
using ll = long long;
vector<pair<ll, ll> > pos;
int par[200010];
int treerank[200010];
void init(int n) {
  for (int i = 0; i < n; i++) {
    par[i] = i;
    treerank[i] = 0;
  }
}
int find(int x) {
  if (par[x] == x) {
    return x;
  } else {
    return par[x] = find(par[x]);
  }
}
void unite(int x, int y) {
  x = find(x);
  y = find(y);
  if (x == y) {
    return;
  }
  if (treerank[x] < treerank[y]) {
    par[x] = y;
  } else {
    par[y] = x;
    if (treerank[x] == treerank[y]) {
      treerank[x]++;
    }
  }
}
bool same(int x, int y) { return find(x) == find(y); }
struct edge {
  int u;
  int v;
  ll cost;
};
vector<edge> es;
bool compedge(const edge& e1, const edge& e2) { return e1.cost < e2.cost; }
ll kruskal() {
  sort(es.begin(), es.end(), compedge);
  init(pos.size());
  ll res = 0;
  for (int i = 0; i < es.size(); i++) {
    edge tempe = es[i];
    if (!same(tempe.u, tempe.v)) {
      unite(tempe.u, tempe.v);
      res += tempe.cost;
    }
  }
  return res;
}
bool compare_by_b(pair<ll, ll> a, pair<ll, ll> b) {
  if (a.second != b.second) {
    return a.second < b.second;
  } else {
    return a.first < b.first;
  }
}
int main() {
  int n;
  cin >> n;
  map<pair<ll, ll>, int> mp;
  for (int i = 0; i < n; i++) {
    ll x, y;
    cin >> x >> y;
    if (mp.find(pair<ll, ll>(x, y)) == mp.end()) {
      mp[pair<ll, ll>(x, y)] = i;
      pos.push_back(pair<ll, ll>(x, y));
    }
  }
  sort(pos.begin(), pos.end());
  for (int i = 1; i < pos.size(); i++) {
    pair<ll, ll> temp1 = pos[i - 1];
    pair<ll, ll> temp2 = pos[i];
    edge e;
    e.u = mp[temp1];
    e.v = mp[temp2];
    e.cost = pos[i].first - pos[i - 1].first;
    es.push_back(e);
  }
  sort(pos.begin(), pos.end(), compare_by_b);
  for (int i = 1; i < pos.size(); i++) {
    pair<ll, ll> temp1 = pos[i - 1];
    pair<ll, ll> temp2 = pos[i];
    edge e;
    e.u = mp[temp1];
    e.v = mp[temp2];
    e.cost = pos[i].second - pos[i - 1].second;
    es.push_back(e);
  }
  ll ans = kruskal();
  cout << ans << endl;
}
