#include<bits/stdc++.h>
#define ll long long
using namespace std;
void solve()
{
    ll n;
    cin>>n;
    vector<vector<ll>>f;
    vector<vector<ll>>s;
     map<ll,vector<ll>>req;
    for(int i=0;i<n;i++){
        ll u,v;
        cin>>u>>v;
        f.push_back({u,v,i});
        s.push_back({v,u,i});
        req[v].push_back(i);
    }
    sort(s.begin(),s.end());
    ll ans=0;
    ll total=0;
    map<ll,ll>marked;
    map<ll,ll>index;
    auto it=req.begin();
    /*for(auto i: req){
        cout<<i.first<<":";
        for(int j: i.second)
            cout<<j<<" ";
        cout<<"\n";
    }
    cout<<"\n";
    for(int i=0;i<n;i++){
        cout<<s[i][0]<<" "<<s[i][1]<<"\n";
    }*/
    for(int i=0;i<n;i++){
        index[s[i][2]]=i;
    }
    for(int i=n-1;i>=0;i--){
        while( total>=(*it).first && it!=req.end()){
            for(int j: (*it).second){
                marked[j]++;
                total+=f[j][0];
                ans+=f[j][0];
                s[index[f[j][2]]][1]=0;
            }
           // cout<<(*it).first<<" * \n";
            //cout<<f[((*it).second)[0]][0] <<"\n";
            //cout<<ans<<" "<<total<<"<-\n";
            it++;
        }
        if(marked[s[i][2]]){
            continue;
        }
        ll x=min(s[i][1],(ll) (*it).first-total );
        s[i][1]-=x;
        f[s[i][2]][0]-=x;
        total+=x;
        ans+=2*x;
      //  cout<<x<<" "<<total<<"<-\n";
        if(s[i][1]){
            i++;
            continue;
        }

        marked[s[i][2]]++;
    }
    cout<<ans<<"\n";
}
int main()
{
    solve();
}
