    #include <bits/stdc++.h>
    using namespace std;
    #define rep(i,n) for(int i=0;i < n;i++)
    typedef long long ll;
    int main(){
        int n;
        cin >> n;
        vector<long long> a(n);
        rep(i,n){
            cin >> a[i];
        }
        vector<vector<bool>> dp(n,vector<bool>(100001,false));
        dp[0][0] = true;
        dp[0][a[0]] = true;
        for(int i=1;i < n;i++){
            for(int j=0;j < 100001;j++){
                if(j-a[i] >= 0 && dp[i-1][j-a[i]]){
                    dp[i][j] = true;
                } 
                if(dp[i-1][j]){
                    dp[i][j] = true;
                }
            }
        }
        long long totaltime = accumulate(a.begin(),a.end(),0L);
        long long besttime = 999999999;
        rep(j,100001){
            if(dp[n-1][j] && abs(totaltime - 2*j) < abs(totaltime - 2*besttime)){
                besttime = j;
            }
        }
        cout << max(besttime,totaltime-besttime) << endl;


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

const int N = 2e5 + 10;
const int INF = 2e9;

int l[N], r[N];
long long f[N], g[N];
int main()
{
	int n;
	cin >> n;
	for (int i = 1; i <= n; ++i)
	{
		l[i] = INF, r[i] = -INF;
	}
	for (int i = 1; i <= n; ++i)
	{
		int x, c;
		cin >> x >> c;
		l[c] = min(l[c], x);
		r[c] = max(r[c], x);
	}
	for (int i = 1, lst = 0; i <= n + 1; ++i)
	{
		//如果不存在的话 直接跳过 
		if (l[i] == INF) 
			continue;
		//走到当前的左边 
		//		上一个的左边+左边走到当前的右边 上一个的右边走到当前的右边 
		f[i] = min(f[lst] + abs(l[lst] - r[i]), g[lst] + abs(r[lst] - r[i])) + r[i] - l[i];
		//走到当前的右边 
		g[i] = min(f[lst] + abs(l[lst] - l[i]), g[lst] + abs(r[lst] - l[i])) + r[i] - l[i];
		lst = i;
	}
	cout << f[n + 1] << endl;
	return 0;
}