#include <bits/stdc++.h>
using namespace std;
template <typename T0, typename T1>
std::ostream& operator<<(std::ostream& os, const map<T0, T1>& v) {
  for (typename map<T0, T1>::const_iterator p = v.begin(); p != v.end(); p++) {
    os << p->first << ": " << p->second << " ";
  }
  return os;
}
template <typename T0, typename T1>
std::ostream& operator<<(std::ostream& os, const pair<T0, T1>& v) {
  os << v.first << ": " << v.second << " ";
  return os;
}
template <typename T>
std::ostream& operator<<(std::ostream& os, const vector<T>& v) {
  for (int i = 0; i < (int)v.size(); i++) {
    os << v[i] << " ";
  }
  return os;
}
template <typename T>
std::ostream& operator<<(std::ostream& os, const vector<vector<T>>& v) {
  for (int i = 0; i < (int)v.size(); i++) {
    os << v[i] << endl;
  }
  return os;
}
template <typename T>
std::ostream& operator<<(std::ostream& os, const set<T>& v) {
  vector<T> tmp(v.begin(), v.end());
  os << tmp;
  return os;
}
template <typename T>
std::ostream& operator<<(std::ostream& os, const deque<T>& v) {
  vector<T> tmp(v.begin(), v.end());
  os << tmp;
  return os;
}
struct UnionFind {
  vector<int> data;
  UnionFind(int size) : data(size, -1) {}
  bool Union(int x, int y) {
    x = root(x);
    y = root(y);
    if (x != y) {
      if (data[y] < data[x]) swap(x, y);
      data[x] += data[y];
      data[y] = x;
    }
    return x != y;
  }
  bool Find(int x, int y) { return root(x) == root(y); }
  int root(int x) { return data[x] < 0 ? x : data[x] = root(data[x]); }
  int size(int x) { return -data[root(x)]; }
};
int main() {
  long long N;
  while (cin >> N) {
    vector<pair<long long, long long>> xs(N), ys(N);
    for (int i = 0, _n = (N); (i) < (int)_n; ++i) {
      xs[i].first =
          (long long)(((100000000 - 1) * (double)rand() / RAND_MAX) + 1);
      ys[i].first =
          (long long)(((100000000 - 1) * (double)rand() / RAND_MAX) + 1);
      xs[i].second = i;
      ys[i].second = i;
    }
    sort((xs).begin(), (xs).end());
    sort((ys).begin(), (ys).end());
    vector<tuple<long long, int, int>> c;
    for (int l = (int)1, _b = (int)(min(N, 1000000 / N)); (l) < _b; ++l)
      for (int i = 0, _n = (N - l); (i) < (int)_n; ++i) {
        int j = i + l;
        if (i < N && j < N) {
          c.push_back(make_tuple(abs(xs[i].first - xs[j].first), xs[i].second,
                                 xs[j].second));
          c.push_back(make_tuple(abs(ys[i].first - ys[j].first), ys[i].second,
                                 ys[j].second));
        }
      }
    sort((c).begin(), (c).end());
    UnionFind uf(N);
    long long ans = 0;
    for (int i = 0, _n = (c.size()); (i) < (int)_n; ++i) {
      long long v;
      int si, ei;
      tie(v, si, ei) = c[i];
      if (!uf.Find(si, ei)) {
        uf.Union(si, ei);
        ans += v;
      }
    }
    cout << ans << endl;
    break;
  }
  return 0;
}
