#include <bits/stdc++.h>
using namespace std;
#define rep(i, n) for(int i = 0; i < n; i++)
#define rep2(i, x, n) for(int i = x; i <= n; i++)
#define rep3(i, x, n) for(int i = x; i >= n; i--)
#define each(e, v) for(auto &e: v)
#define pb push_back
#define eb emplace_back
#define all(x) x.begin(), x.end()
#define rall(x) x.rbegin(), x.rend()
#define sz(x) (int)x.size()
using ll = long long;
using pii = pair<int, int>;
using pil = pair<int, ll>;
using pli = pair<ll, int>;
using pll = pair<ll, ll>;
const int MOD = 1000000007;
//const int MOD = 998244353;
const int inf = (1<<30)-1;
const ll INF = (1LL<<60)-1;
template<typename T> bool chmax(T &x, const T &y) {return (x < y)? (x = y, true) : false;};
template<typename T> bool chmin(T &x, const T &y) {return (x > y)? (x = y, true) : false;};

struct io_setup{
    io_setup(){
        ios_base::sync_with_stdio(false);
        cin.tie(NULL);
        cout << fixed << setprecision(15);
    }
} io_setup;

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

    vector<ll> L(N+2, INF), R(N+2, -INF);
    L[0] = 0, R[0] = 0, L[N+1] = 0, R[N+1] = 0;

    rep(i, N){
        ll x; int c; cin >> x >> c;
        chmin(L[c], x), chmax(R[c], x);
    }

    vector<vector<ll>> dp(N+2, vector<ll>(2, INF));
    dp[0][0] = 0, dp[0][1] = 0;

    int pre = 0;

    rep2(i, 1, N+1){
        if(L[i] == INF) {dp[i][0] = dp[pre][0], dp[i][1] = dp[pre][1]; continue;}

        chmin(dp[i][0], dp[pre][0]+abs(R[i]-L[pre])+abs(L[i]-R[i]));
        chmin(dp[i][1], dp[pre][0]+abs(L[i]-L[pre])+abs(R[i]-L[i]));

        chmin(dp[i][0], dp[pre][1]+abs(R[i]-R[pre])+abs(L[i]-R[i]));
        chmin(dp[i][1], dp[pre][1]+abs(L[i]-R[pre])+abs(R[i]-L[i]));

        pre = i;
    }

    //rep(i, N+2) cout << dp[i][0] << ' ' << dp[i][1] << '\n';

    cout << min(dp[N+1][0], dp[N+1][1]) << '\n';
}
#include <bits/stdc++.h>

#define int long long
#define fastio ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0);

using namespace std;

signed main(){
    fastio
    //Equivalent to the problem which we need to collect from the top of the grid down
    int n;
    cin >> n;
    int l[n+1], r[n+1];
    fill(l,l+n+1,1e18);
    fill(r,r+n+1,-1e18);
    for(int i = 0;i < n;i++){
        int x,c;
        cin >> x >> c;
        l[c] = min(l[c],x);
        r[c] = max(r[c],x);
    }
    l[0] = r[0] = 0;
    int dp[n+1][2] = {}; //dp[i][0] => start from left, dp[i][1] start from right
    for(int i = 1;i <= n;i++){
        dp[i][0] = dp[i-1][0], dp[i][1] = dp[i-1][1];
        if(l[i]==1e18){
            l[i] = l[i-1], r[i] = r[i-1];
            continue;   
        }
        dp[i][0] = min(dp[i-1][0]+abs(l[i]-r[i-1])+r[i]-l[i],dp[i-1][1]+abs(l[i]-l[i-1])+r[i]-l[i]);
        dp[i][1] = min(dp[i-1][0]+abs(r[i]-r[i-1])+r[i]-l[i],dp[i-1][1]+abs(r[i]-l[i-1])+r[i]-l[i]);
    }
    cout << min(dp[n][0]+abs(r[n]),dp[n][1]+abs(l[n])) << "\n";
}