#include <bits/stdc++.h>
int t1, t2, t3;
int n;
int x[100005];
int y[100005];
std::map<int, int> xi, yi;
std::map<int, int>::iterator it;
std::vector<std::pair<int, std::pair<int, int> > > g;
void push(int u, int v) {
  t2 = (x[u] >= x[v] ? x[u] - x[v] : x[v] - x[u]);
  t3 = (y[u] >= y[v] ? y[u] - y[v] : y[v] - y[u]);
  g.push_back({(t2 <= t3 ? t2 : t3), {u, v}});
}
int lv[100005];
int up[100005];
int get(int u) {
  if (up[u] != up[up[u]]) return up[u] = get(up[u]);
  return up[u];
}
int ans = 0;
int main() {
  scanf("%d", &n);
  for (int i = 0; i < n; i++) {
    scanf("%d%d", x + i, y + i);
    xi[x[i]] = i;
    yi[y[i]] = i;
    up[i] = i;
  }
  it = xi.begin();
  t1 = it->second;
  for (++it; it != xi.end(); ++it) {
    push(t1, it->second);
    t1 = it->second;
  }
  it = yi.begin();
  t1 = it->second;
  for (++it; it != yi.end(); ++it) {
    push(t1, it->second);
    t1 = it->second;
  }
  std::sort(g.begin(), g.end());
  for (std::pair<int, std::pair<int, int> > e : g) {
    t1 = get(e.second.first);
    t2 = get(e.second.second);
    if (t1 != t2) {
      ans += e.first;
      if (lv[t1] < lv[t2])
        up[t1] = t2;
      else if (lv[t1] > lv[t2])
        up[t2] = t1;
      else {
        up[t1] = t2;
        lv[t2]++;
      }
    }
  }
  printf("%d", ans);
}
