#include<bits/stdc++.h>
using namespace std;
#define pb push_back
#define ff first
#define ss second
#define mp make_pair
typedef long long int ll;
int main()
{
#ifndef ONLINE_JUDGE
	freopen("input.txt", "r", stdin);
	freopen("output.txt", "w", stdout);
#endif

	ll n, m; cin >> n >> m;
	ll a[n][m];
	ll mi = 9999;
	ll sum = 0;
	for (int i = 0; i < n; i++) {
		for (int j = 0; j < m; j++) {
			cin >> a[i][j];
			sum += a[i][j];
			mi = min(mi, a[i][j]);
		}
	}
	cout << sum - mi*(n * m);
}
#include <bits/stdc++.h>
using namespace std;
#define ll long long
#define rep(i,n) for(int (i)=0;(i)<(n);(i)++)
#define P pair<int,int>
#define Tp tuple<int,int,int>
using Graph = vector<vector<int>>;

int main(){
    int N; cin >> N;
    ll left[N+1],right[N+1]; bool col[N+1];
    rep(i,N+1){
        left[i] = 1000000001;
        right[i] = -1000000001;
        col[i] = false;
    } 
    rep(i,N){
        ll x,c; cin >> x >> c;
        col[c] = true;
        left[c] = min(left[c],x);
        right[c] = max(right[c],x);
    }
    ll s1 = 0,s2 = 0;
    ll dp[N+1][2];
    rep(i,2){
        rep(j,N+1){
            dp[j][i] = 200000000000000000;
        }
    }
    dp[0][0] = 0; dp[0][1] = 0;
    rep(i,N){
        if(!col[i+1]){
            dp[i+1][0] = dp[i][0];
            dp[i+1][1] = dp[i][1]; continue;
        }
        ll len = right[i+1]-left[i+1];
        dp[i+1][0] = min(dp[i][0]+abs(s1-right[i+1]),dp[i][1]+abs(s2-right[i+1]));
        dp[i+1][1] = min(dp[i][0]+abs(s1-left[i+1]),dp[i][1]+abs(s2-left[i+1]));
        s1 = left[i+1]; s2 = right[i+1];
        dp[i+1][0] += len; dp[i+1][1] += len;
    }
    cout << min(dp[N][0]+abs(s1),dp[N][1]+abs(s2)) << endl;
}