// E - Traveler
#include <bits/stdc++.h>
using namespace std;
using ll = int64_t;
#define rep(i,e) for(int i=0;i<(e);++i)

int main(){
	ll INF = 1e9 + 1;
	int n; cin>>n;
	vector<pair<ll,ll>> A(n+1);
	rep(i, n) A[i] = {INF, -INF};
	rep(i, n){
		ll x, c; cin>>x>>c; --c;
		auto[mn, mx] = A[c];
		A[c] = {min(mn, x), max(mx, x)};
	}

	ll pre_mn, pre_mx;
	int pre = -1;
	rep(now, n+1){
		auto[mn, mx] = A[now];
		if(mn == INF) continue;
		ll p_mn = 0, p_mx = 0;
		if(pre < 0) pre_mn = pre_mx = 0;
		else tie(p_mn, p_mx) = A[pre];
		ll a = pre_mn + abs(p_mn - mn);
		ll b = pre_mn + abs(p_mn - mx);
		ll c = pre_mx + abs(p_mx - mn);
		ll d = pre_mx + abs(p_mx - mx);
		ll e = mx - mn;
		pre_mn = min(b, d) + e;
		pre_mx = min(a, c) + e;
		pre = now;
	}
	cout<< pre_mn <<endl;
}

//AnkitCode99 here....
//every ups and downs matter!

#include<bits/stdc++.h>
#define endl "\n"
#define IOS ios_base::sync_with_stdio(0);cin.tie(nullptr);cout.tie(nullptr)
typedef long long int ll;
#define rep(i,a,b) for(ll i=a;i<b;i++)
#define pb push_back

using namespace std;

const ll sz=(1e5+5)*2;
const ll szz=1e6+6;
const ll mod=1e9+7;

ll C[sz][2],dp[sz][2];

ll ss;

ll solve(ll pos,ll flag)
{
    if(pos==0)
    {
        return 0;
    }

    ll &ans = dp[pos][flag];
    if(ans!=-1)
        return ans;

    ans = abs(C[pos][0]-C[pos][1]);
    ans+=min(solve(pos-1,0)+abs(C[pos-1][0] - C[pos][flag^1]), solve(pos-1,1)+abs(C[pos-1][1] - C[pos][flag^1]));
    return ans;
}

int main()
{
    IOS;

    #ifndef ONLINE_JUDGE
    freopen("input.txt","r",stdin);
    freopen("op.txt","w",stdout);
    #endif

    clock_t startTime=clock();

    ll n;
    cin>>n;
    ll ar[n];
    map<ll,ll> l,r;
    rep(i,0,n)
    {
        ll x,c;
        cin>>x>>c;
        if(l.count(c))
        {
            l[c]=min(l[c],x);
            r[c]=max(r[c],x);
        }
        else
        {
            l[c]=r[c]=x;
        }
    }

    ss=0;
    for(auto x:l)
    {
        C[++ss][0]=x.second;
        C[ss][1]=r[x.first];
    }


    memset(dp,-1,sizeof dp);
    cout<<solve(ss+1,0);

    cerr << endl <<setprecision(20)<< double( clock() - startTime ) / (double)CLOCKS_PER_SEC<< " seconds." << endl;

}//Goodbye...