#include <algorithm>
#include <cfloat>
#include <climits>
#include <cstring>
#include <cmath>
#include <deque>
#include <functional>
#include <iostream>
#include <map>
#include <numeric>
#include <queue>
#include <set>
#include <sstream>
#include <stack>
#include <string>
#include <vector>
# ifdef __GNUC__
# if __cplusplus > 199711L
# include <unordered_set>
# include <unordered_map>
# else
# include <tr1/unordered_map>
# include <tr1/unordered_set>
using namespace tr1;
# endif
# else
# include <unordered_map>
# include <unordered_set>
# endif
using namespace std;

#define fi first
#define se second
#define FO(x, n) for (int x = 0; x < n; ++x)
#define FOR(x, a, b) for (int x = a; x < b; ++x)
#define RFO(x, n) for (int x = n - 1; x >= 0; --x)
#define RFOR(x, a, b) for (int x = b - 1; x >= a; --x)
typedef unsigned char byte;
typedef unsigned int uint;
typedef long long llong;
typedef unsigned long long ullong;
typedef pair<int, int> pii;
typedef pair<double, double> pdd;
typedef pair<llong, llong> pll;
inline bool feq(const double& a, const double& b) { return fabs(a - b) < 1e-10; }

const int MAXN = 100100;
int N;
pii pos[MAXN];
bool in[MAXN];
vector<int> edge[MAXN];
unordered_map<int, unordered_set<int>> has;

int dist(int a, int b)
{
    return min(abs(pos[a].fi - pos[b].fi), abs(pos[a].se - pos[b].se));
}

int main()
{
    while (cin >> N)
    {
        has.clear();
        memset(in, 0, sizeof(in));
        xs.clear();
        ys.clear();
        FO (i, N)
        {
            int x, y;
            cin >> x >> y;
            if (has[x].count(y))
                in[i] = true;
            has[x].insert(y);
        }
        priority_queue<pii, vector<pii>, greater<pii>> que;
        in[0] = true;
        FO (i, N)
            if (!in[i])
                que.push(pii(dist(0, i), i));
        llong res = 0;
        while (!que.empty())
        {
            pii d_u = que.top();
            que.pop();
            int d = d_u.fi;
            int u = d_u.se;
            if (in[u])
                continue;
            res += d;
            in[u] = true;
            FO (i, N)
                if (!in[i])
                    que.push(pii(dist(u, i), i));
        }
        cout << res << endl;
    }
    return 0;
}