#include <bits/stdc++.h>

using namespace std;

int main()
{
	int n;
	cin>>n;
	int a[n][n] = {0};
	int c[n] = {0};
	queue<int> p;
	queue<int> v;
	int r = 0;
	for(int i = 0;i<n;i++)
	{
		int k,m;
		cin>>k>>m;
		a[k][m] = 1;
		c[m]++;
	}
	for(int i = 0;i<n;i++)
	{
		if(c[i]==0)
		{
			if(!v.empty())
			{
				r+=(abs(v.front()-i));
				c[i]++;
				c[v.front()]--;
				v.pop();
			}
			else
			{
				p.push(i);
			}
		}
		if(c[i]>1)
		{
			if(!p.empty())
			{
				r+=(abs(p.front()-i));
				c[i]++;
				c[p.front()]--;
				p.pop();
			}
			else
			{
				v.push(i);
			}
		}
	}
	cout<<r;
}