#include "bits/stdc++.h"
using namespace std;
#define rep(i,n) for(int i=0;i<n;i++)
#define sor(v) sort(v.begin(),v.end())
#define rev(s) reverse(s.begin(),s.end())
#define L long long

int main() {
	int m; cin >> m;
	static const int n = m;
	vector<vector<L>> v(n);
	rep(i, n) {
		L x, c; cin >> x >> c;
		c--;
		v[c].push_back(x);
	}
	L p1 = 0, p2 = 0, t1 = 0, t2 = 0;
	rep(i, n) {
		if (v[i].size() == 0) continue;
		sor(v[i]);
		L xmin = v[i][0], xmax = v[i][v[i].size() - 1];
		L d = xmax - xmin;
		L t1_ = min(t1 + abs(xmax - p1) + d, t2 + abs(xmax - p2) + d);
		L t2_ = min(t1 + abs(xmin - p1) + d, t2 + abs(xmin - p2) + d);
		p1 = xmin;
		p2 = xmax;
		t1 = t1_; t2 = t2_;
	}
	L ans = min(t1 + abs(p1), t2 + abs(p2));
	cout << ans << endl;
	
}
#include <bits/stdc++.h>
using namespace std;

#define ll long long
#define ar array

const int mxN=1.5e6;
int n, m, a[mxN], cnt[mxN];

int main() {
	ios::sync_with_stdio(0);
	cin.tie(0);
	cin >> n >> m;
	for (int i=0; i<n; ++i)
		cin >> a[i];
	for (int i=0; i<m; ++i)
		++cnt[a[i]];
	int cur=0;
	while(cur<n&&cnt[cur])
		++cur;
	int ans=cur;
	for (int i=m; i<n; ++i) {
		++cnt[a[i]];
		if (--cnt[a[i-m]]==0)
			ans=min(ans, a[i-m]);
	}
	cout << ans;
	return 0;
}
