#include <iostream>
#include <vector>
#include <numeric>
#include <algorithm>

int main(void)
{
  int N;
  std::cin >> N;

  std::vector<std::pair<int, int> > x(N), y(N);
  for(int i = 0; i < N; ++i){
    int a, b;
    std::cin >> a >> b;
    x[i] = std::make_pair(i, a);
    y[i] = std::make_pair(i, b);
  }

  std::sort(x.begin(), x.end(), [](auto const& lhs, auto const& rhs){ return lhs.second < rhs.second; });
  std::sort(y.begin(), y.end(), [](auto const& lhs, auto const& rhs){ return lhs.second < rhs.second; });

  struct Cost{ int cost; int left; int right; };
  std::vector<Cost> cost((N-1)*2);
  for(int i = 0; i < N-1; ++i){
    cost[i*2] = {x[i+1].second-x[i].second, x[i].first, x[i+1].first};
    cost[i*2+1] = {y[i+1].second-y[i].second, y[i].first, y[i+1].first};
  }

  std::vector<bool> checked(N, false);
  int sumCost = 0;

  while(std::find(checked.begin(), checked.end(), false) != checked.end()){
    auto minElem = std::min_element(cost.begin(), cost.end(), [](auto const& lhs, auto const& rhs){ return lhs.cost < rhs.cost; });

    if(checked[minElem->left] && checked[minElem->right]){ cost.erase(minElem); continue; }

    checked[minElem->left] = true;
    checked[minElem->right] = true;
    sumCost += minElem->cost;
    cost.erase(minElem);
  }

  std::cout << sumCost << std::endl;

  return 0;
}

