#include<bits/stdc++.h>
#define maxn 200010
using namespace std;

int n, ans;
vector<int> r[maxn], c[maxn];
set<int> rHave, rMiss, cHave, cMiss;

void getOne(){
	while(rMiss.size()){
		int tmp = *rMiss.begin();
		rMiss.erase(rMiss.begin());
		int lB = -400000, rB = -400000;
		set<int>::iterator tmpB = rHave.lower_bound(tmp);
		if(tmpB == rHave.end()){
			lB = *(--tmpB);
		} else {
			rB = *tmpB;
			if(tmpB != rHave.begin()){
				lB = *(--tmpB);
			}
		}
		if(abs(tmp-lB) > abs(tmp-rB)){
			swap(lB, rB);
		}
		ans += abs(tmp-lB);
		r[tmp].push_back(r[lB].back());
		r[lB].pop_back();
		if(!r[lB].size()){
			rHave.erase(lB);
			rMiss.insert(lB);
		}
	}
}

int main(){
	ios_base::sync_with_stdio(0);
	cout.tie(0);
	cin.tie(0);
	cin >> n;
	for(int i = 0; i < n; ++i){
		int x, y;
		cin >> x >> y;
		r[x].push_back(y);
		rHave.insert(x);
	}
	for(int i = 1; i < n+1; ++i){
		if(rHave.find(i) == rHave.end()){
			rMiss.insert(i);
		}
	}
	getOne();
	rMiss.clear();
	rHave.clear();
	for(int i = 1; i < n+1; ++i){
		for(auto j : r[i]){
			c[j].push_back(i);
			rHave.insert(j);
		}
	}
	for(int i = 1; i < n+1; ++i){
		r[i] = c[i];
		if(rHave.find(i) == rHave.end()){
			rMiss.insert(i);
		}
	}
	getOne();
	cout << ans;
}