#include <bits/stdc++.h>
#define li long long int
#define lp(i,a,b) for(li i=a;i<b;i++)
using namespace std;
const li inf = 1e18+7;
void solve(){
    li n,m,mn=inf,ans=0;
    cin>>n>>m;
    li a[n][m];
    lp(i,0,n)
        lp(j,0,m){
            cin>>a[i][j];
            mn=min(a[i][j],mn);
        } 
    lp(i,0,n)
        lp(j,0,m){
            if(a[i][j]!=mn) ans+=(a[i][j]-mn);
        }     
    cout<<ans<<"\n";
}
int main()
{   ios_base::sync_with_stdio(0); 
    cin.tie(0); 
    cout.tie(0);
    // li t=1;
    // cin>>t;
    // while(t--){
        solve();
   // }

    return 0;
}
#include <iostream>
#include <vector>
#include <array>
#include <list>
#include <queue>
#include <stack>
#include <set>
#include <map>
#include <unordered_map>
#include <unordered_set>
#include <utility>
#include <string>
#include <sstream>
#include <algorithm>
#include <random>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <ctime>
#include <cmath>
#include <cassert>
#include <climits>
#include <bitset>
#include <functional>
#include <iomanip>
#include <random>

#define FOR_LT(i, beg, end) for (decltype(end) i = beg; i < end; i++)
#define FOR_LE(i, beg, end) for (decltype(end) i = beg; i <= end; i++)
#define FOR_DW(i, beg, end) for (decltype(beg) i = beg; end <= i; i--)
#define REP(n)              for (decltype(n) repeat_index = 0; repeat_index < n; repeat_index++)

using namespace std;

template<typename T, size_t S>
T minval(const T(&vals)[S])
{
	T val = numeric_limits<T>::max();
	FOR_LT(i, 0, S) {
		val = min(val, vals[i]);
	}
	return val;
}

template<typename T, size_t S>
T maxval(const T(&vals)[S])
{
	T val = numeric_limits<T>::min();
	FOR_LT(i, 0, S) {
		val = max(val, vals[i]);
	}
	return val;
}

int main()
{
	ios_base::sync_with_stdio(false);
	cin.tie(NULL);
	cout << fixed << setprecision(20);

	int n; cin >> n;

	vector<int64_t> minc(n + 1, INT64_MAX);
	vector<int64_t> maxc(n + 1, INT64_MIN);
	vector<bool> hasb(n + 1);
	minc[0] = 0;
	maxc[0] = 0;

	FOR_LT(i, 0, n) {
		int64_t x, c; cin >> x >> c;
		hasb[c] = true;
		minc[c] = min(minc[c], x);
		maxc[c] = max(maxc[c], x);
	}

	vector<array<int64_t, 2>> dp(n + 2, { INT64_MAX, INT64_MAX });
	dp[0][0] = 0; dp[0][1] = 0;
	int pc = 0;
	FOR_LE(i, 0, n) {
		if (!hasb[i]) {
			dp[i + 1][0] = dp[i][0];
			dp[i + 1][1] = dp[i][1];
			continue;
		}
		//cout << minc[pc] << " " << maxc[pc] << " " << minc[i] << " " << maxc[i] << endl;

		{
			dp[i + 1][0] = min(dp[i + 1][0], dp[i][0] + abs(minc[pc] - maxc[i]) + abs(minc[i] - maxc[i]));
			dp[i + 1][1] = min(dp[i + 1][1], dp[i][0] + abs(minc[pc] - minc[i]) + abs(minc[i] - maxc[i]));
		}
		{
			dp[i + 1][0] = min(dp[i + 1][0], dp[i][1] + abs(maxc[pc] - maxc[i]) + abs(minc[i] - maxc[i]));
			dp[i + 1][1] = min(dp[i + 1][1], dp[i][1] + abs(maxc[pc] - minc[i]) + abs(minc[i] - maxc[i]));
		}
		//cout << dp[i + 1][0] << " " << dp[i + 1][1] << endl;
		pc = i;
	}

	cout << min(dp[n + 1][0] + abs(minc[pc]), dp[n + 1][1] + abs(maxc[pc])) << endl;

	return 0;
}