#include <bits/stdc++.h>
#define REP(i,n) for(ll i=0;i<(ll)(n);i++)
#define REPD(i,n) for(ll i=n-1;i>=0;i--)
#define FOR(i,a,b) for(ll i=a;i<=(ll)(b);i++)
#define FORD(i,a,b) for(ll i=a;i>=(ll)(b);i--)
#define ALL(x) (x).begin(),(x).end()
#define RALL(x) (x).rbegin(),(x).rend()
#define SIZE(x) ((ll)(x).size())
#define MAX(x) *max_element(ALL(x))
#define MIN(x) *min_element(ALL(x))
using namespace std;
template<class T> inline bool chmax(T& a, T b) { if (a < b) { a = b; return true; } return false; }
template<class T> inline bool chmin(T& a, T b) { if (a > b) { a = b; return true; } return false; }
typedef long long ll;
const ll LINF = INT64_MAX;
const int IINF = INT32_MAX;
using P = pair<int, int>;

int main() {
    int n;
    cin >> n;

    vector<int> l(n, IINF), r(n, -IINF);
    REP(i, n){
        int x, c;
        cin >> x >> c;
        --c;
        chmin(l[c], x);
        chmax(r[c], x);
    }
    
    vector<P> d;
    d.emplace_back(0, 0);
    REP(i, n) if(l[i] != IINF){
        d.emplace_back(l[i], r[i]);
    }
    d.emplace_back(0, 0);

    vector<ll> dp(2);
    FOR(i, 1, SIZE(d)-1){
        vector<ll> p(2, LINF);
        swap(p, dp);

        int L = d[i].first, R = d[i].second;
        REP(j, 2){
            int x = j ? d[i-1].second : d[i-1].first;
            chmin(dp[0], p[j] + abs(x-R) + (R-L));
            chmin(dp[1], p[j] + abs(x-L) + (R-L));
        }
    }

    cout << dp[0] << endl;

    return 0;
}
#include<bits/stdc++.h>
using namespace std;
typedef long long ll;

const int maxl=3e5+10;
const ll inf=1ll<<60;

int n,m,k,cnt,tot,cas,ans;
struct node
{
	int x,c;
}a[maxl];
int l[maxl],r[maxl];
ll dp[maxl][2];
bool vis[maxl];
char s[maxl];

inline bool cmp(const node &a,const node &b)
{
	return a.x<b.x;
}

inline void prework()
{
	scanf("%d",&n);
	for(int i=1;i<=n;i++)
	{
		scanf("%d%d",&a[i].x,&a[i].c);
		if(l[a[i].c]==0)
			l[a[i].c]=r[a[i].c]=a[i].x;
		else
			l[a[i].c]=min(l[a[i].c],a[i].x),
			r[a[i].c]=max(r[a[i].c],a[i].x);
	}
}

inline void chmi(ll &x,ll y)
{
	x=min(x,y);
}

inline void mainwork()
{
	for(int i=1;i<=n;i++)
	if(l[i]==0)
	{
		l[i]=l[i-1];dp[i][0]=dp[i-1][0];
		r[i]=r[i-1];dp[i][1]=dp[i-1][1];
	}
	else
	{
		dp[i][0]=dp[i][1]=inf;
		chmi(dp[i][0],dp[i-1][0]+abs(r[i]-l[i-1])+r[i]-l[i]);
		chmi(dp[i][0],dp[i-1][1]+abs(r[i]-r[i-1])+r[i]-l[i]);
		chmi(dp[i][1],dp[i-1][0]+abs(l[i]-l[i-1])+r[i]-l[i]);
		chmi(dp[i][1],dp[i-1][1]+abs(l[i]-r[i-1])+r[i]-l[i]);
	}
}

inline void print()
{
	ll ans=min(dp[n][0]+abs(l[n]),dp[n][1]+abs(r[n]));
	printf("%lld",ans);
}

int main()
{
	int t=1;
	//scanf("%d",&t);
	for(cas=1;cas<=t;cas++)
	{
		prework();
		mainwork();
		print();
	}
	return 0;
}