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

typedef long long int LL;
typedef long int LI;

int main() {
  int q;
  cin >> q;
  unordered_map<int, int> mp;
  unordered_map<int, int> :: iterator it;
  while(q--) {
    char t;
    int num;
    cin >> t >> num;
    if(t == 'L') {
      mp[num] = 0;
      for(it=next(mp.begin()); it!=mp.end(); it++) { //O(2*1e5)) --> when all queries are 'L'
        mp[it->first]++;
      }
    } else if (t=='R') { //O(1)
      mp[num] = mp.size();
    } else if (t=='?') { //O(1)
      if(mp[num] < mp.size()-mp[num]-1) {
        cout << mp[num] << "\n";
      } else {
        cout << (mp.size()-mp[num]-1) << "\n";
      }
    }
  }
  return 0;
}


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

typedef long long int LL;
typedef long int LI;

int main() {
  int q;
  cin >> q;
  unordered_map<int, int> mp;
  int l=0, r=0;
  for(int i=0; i<q; i++) {
    char t;
    int num;
    cin >> t >> num;
    if(i==0) {
    	mp[num]=0;
    	r++;
    	l--;
    } else if(t == 'L') {//O(1)
      mp[num] = l;
      l--;
    } else if (t=='R') { //O(1)
      mp[num] = r;
      r++;
    } else if (t=='?') { //O(1)
    //   int rightIdx = r-1-mp[num];
    //   int leftIdx = -1*l-1+mp[num];
      if((-1*l-1+mp[num]) < (r-1-mp[num])) {
      	cout << (-1*l-1+mp[num]) << "\n";
      } else {
      	cout << (r-1-mp[num]) << "\n";
      }
    }
  }
  return 0;
}


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

typedef long long int LL;
typedef long int LI;

int main() {
  LL q;
  cin >> q;
  unordered_map<LL, LL> mp;
  int l=0, r=0;
  for(int i=0; i<q; i++) {
    char t;
    int num;
    cin >> t >> num;
    if(i==0) {
    	mp[num]=0;
    	r++;
    	l--;
    } else if(t == 'L') {//O(1)
      mp[num] = l;
      l--;
    } else if (t=='R') { //O(1)
      mp[num] = r;
      r++;
    } else if (t=='?') { //O(1)
      int rightIdx = r-1-mp[num];
      int leftIdx = -1*l-1+mp[num];
      if(leftIdx < rightIdx) {
      	cout << leftIdx << "\n";
      } else {
      	cout << rightIdx << "\n";
      }
    }
  }
  return 0;
}


#include <bits/stdc++.h>

using namespace std;

int main(){
	int q;
	cin >> q;
	int L = -1, R = 0;
	unordered_map<int, int> hm;

	char type;
	int id;
for(int i = 0; i < q; i++){
	cin >> type >> id;
	if(type == 'L'){
		hm[id] = L;
L--;
}else if(type == 'R'){
	hm[id] = R;
	R++;
}else{
	cout << min(hm[id] - L, R - hm[id]) - 1 << “\n”;
}
}
}


#include <bits/stdc++.h>

using namespace std;

int main(){
    ios_base::sync_with_stdio(0);
    cin.tie(0);
	int q;
	cin >> q;
	int L = -1, R = 0;
    int hm[200002];

	char type;
	int id;
for(int i = 0; i < q; i++){
	cin >> type >> id;
	if(type == 'L'){
		hm[id] = L;
L--;
}else if(type == 'R'){
	hm[id] = R;
	R++;
}else{
	cout << min(hm[id] - L, R - hm[id]) - 1 << "\n";
}
}
}


#include <bits/stdc++.h>

using namespace std;

int main(){
    ios_base::sync_with_stdio(0);
    cin.tie(0);
	int q;
	cin >> q;
	int L = -1, R = 0;
    vector<int> hm(200002);

	char type;
	int id;
for(int i = 0; i < q; i++){
	cin >> type >> id;
	if(type == 'L'){
		hm[id] = L;
L--;
}else if(type == 'R'){
	hm[id] = R;
	R++;
}else{
	cout << min(hm[id] - L, R - hm[id]) - 1 << "\n";
}
}
}


#include <bits/stdc++.h>

using namespace std;

int main(){
	int q;
	cin >> q;
	int L = -1, R = 0;
	unordered_map<int, int> hm;

	char type;
	int id;
for(int i = 0; i < q; i++){
	cin >> type >> id;
	if(type == 'L'){
		hm[id] = L;
L--;
}else if(type == 'R'){
	hm[id] = R;
	R++;
}else{
	cout << min(hm[id] - L, R - hm[id]) - 1 << "\n";
}
}
}


#include <bits/stdc++.h>

using namespace std;

int main(){
    ios_base::sync_with_stdio(0);
    cin.tie(0);
	int q;
	cin >> q;
	int L = -1, R = 0;
	unordered_map<int, int> hm;

	char type;
	int id;
for(int i = 0; i < q; i++){
	cin >> type >> id;
	if(type == 'L'){
		hm[id] = L;
L--;
}else if(type == 'R'){
	hm[id] = R;
	R++;
}else{
	cout << min(hm[id] - L, R - hm[id]) - 1 << "\n";
}
}
}


#include<bits/stdc++.h>
using namespace std;
int main()
{
    int q,x;char upit;
    vector<int> v;
    cin >> q;
    map<int,int> m;int l=0,d=0;
      cin >> upit >> x;
        if(upit == 'L')
        {
            m[x]=l;
            l--;
            d++;
        }
        else if(upit =='R')
        {
            m[x]=d;
            d++;
            l--;
        }
        else
        {
            int rez = min(d - m[x],m[x]-l)-1;
            cout << rez;
        }
    for(int i=0;i<q-1;i++)
    {
        cin >> upit >> x;
        if(upit == 'L')
        {
            m[x]=l;
            l--;
        }
        else if(upit =='R')
        {
            m[x]=d;
            d++;
        }
        else
        {
            int rez = min(d - m[x],m[x]-l)-1;
            v.push_back(rez);
        }
    }
    for(int i=0;i<v.size();i++)
    {
        cout << v[i]<< endl;
    }
}


#include<bits/stdc++.h>
using namespace std;
int main()
{
    int q;
    cin >> q;int l=0,d=0;
    map<int,int> m;
    char u;
    cin >> u;
    int x1;cin >> x1;
    m[x1]=0;
    for(int i=1;i<q;i++)
    {
        char upit;
        cin >> upit;
        if(upit == 'L')
        {
          int x;cin>> x;
          l--;
          m[x]=l;

        }
        else if(upit == 'R')
        {
            int x;cin >> x;
            d++;
            m[x]=d;

        }
        else
        {
            int x;cin >> x;
            int rez = min(d-m[x],m[x]-l);
            cout << rez;
        }
    }
}


#include<bits/stdc++.h>
using namespace std;
int main()
{
    int q;
    cin >> q;int l=0,d=0;
    map<int,int> m; vector<int> v;
    char u;
    cin >> u;
    int x1;cin >> x1;
    m[x1]=0;
    for(int i=1;i<q;i++)
    {
        char upit;
        cin >> upit;
        if(upit == 'L')
        {
          int x;cin>> x;
          l--;
          m[x]=l;

        }
        else if(upit == 'R')
        {
            int x;cin >> x;
            d++;
            m[x]=d;

        }
        else
        {
            int x;cin >> x;
            int rez = min(d-m[x],m[x]-l);
            v.push_back(rez);
        }
    }
    for(int i=0;i<v.size();i++)
    {
        cout << v[i] << endl;
    }
}


#include<bits/stdc++.h>
using namespace std;
int main()
{
    int q,x;char upit;
    vector<int> v;
    cin >> q;
    map<int,int> m;int l=0,d=0;
      cin >> upit >> x;
        if(upit == 'L')
        {
            m[x]=l;
            l--;
            d++;
        }
        else if(upit =='R')
        {
            m[x]=d;
            d++;
            l--;
        }
        else
        {
            int rez = min(d - m[x],m[x]-l)-1;
            cout << rez;
        }
    for(int i=0;i<q-1;i++)
    {
        cin >> upit >> x;
        if(upit == 'L')
        {
            m[x]=l;
            l--;
        }
        else if(upit =='R')
        {
            m[x]=d;
            d++;
        }
        else
        {
            int rez = min(d - m[x],m[x]-l)-1;
            v.push_back(rez);
        }
    }
    for(int i=0;i<v.size();i++)
    {
        cout << v[i];
    }
}


#include<bits/stdc++.h>
using namespace std;
int main()
{
     unordered_map<int,pair<int,int> > m;
    int q,x;char upit;
    vector<int> v;
    cin >> q;
    for(int i=0;i<q;i++)
    {
        cin >> upit >> x;
        if(upit == 'L')
        {
            map<int,pair<int,int> > :: iterator it;
            for( it = m.begin();it != m.end();it++)
            {
                (*it).second.first ++;
            }
            m[x]= make_pair(0,m.size());
        }
         else if(upit == 'R')
        {
            map<int,pair<int,int> > :: iterator it;
            for( it = m.begin();it != m.end();it++)
            {
                (*it).second.second ++;
            }
            m[x]= make_pair(m.size(),0);
        }
        else
        {
            v.push_back(min(m[x].second,m[x].first));
        }
    }
    int vel = v.size();
    for(int i=0;i<vel;i++)
    {
        cout << v[i] << endl;
    }
}


#include <bits/stdc++.h>
using namespace std;
typedef long long ll;

void solve()
{
    ll n , l,r;
    l=0,r=0;
    cin >> n;
    map<ll ,ll> m;

    while(n--)
    {
        ll x ; char s;
        cin >> s >> x;
        if(l==r)
        {
            m[x]=0;
            l--;
            r++;

        }
       else if(s=='L')
        {
            m[x]=l;
            l--;
        }
        else if(s=='R')
        {
            m[x]=r;
            r++;
        }
        else
        {
            cout << min(m[x] - l ,r-m[x] )-1 << endl;
        }
    }

}
int main(){
	int t=1;
	//cin >> t;
	while(t--)
		solve();
	return 0;
}


#include <bits/stdc++.h>
using namespace std;
typedef long long ll;

void solve()
{
    int n , l,r;
    l=-1,r=1;
    cin >> n;
    map<int ,int > m;
    while(n--)
    {
        int x ; char s;
        cin >> s >> x;
        if(s=='L')
        {
            m[x]=l;
            l--;
        }
        else if(s=='R')
        {
            m[x]=r;
            r++;
        }
        else
        {
            cout << min(m[x] - l ,r-m[x] )-1 << endl;
        }
    }

}
int main(){
	int t=1;
	//cin >> t;
	while(t--)
		solve();
	return 0;
}


#include <bits/stdc++.h>
using namespace std;
typedef long long ll;

void solve()
{
    ll n , l,r;
    l=-1,r=1;
    cin >> n;
    map<int ,int > m;
    while(n--)
    {
        ll x ; char s;
        cin >> s >> x;
        if(s=='L')
        {
            m[x]=l;
            l--;
        }
        else if(s=='R')
        {
            m[x]=r;
            r++;
        }
        else
        {
            cout << min(m[x] - l ,r-m[x] )-1 << endl;
        }
    }

}
int main(){
	int t=1;
	//cin >> t;
	while(t--)
		solve();
	return 0;
}


#include <bits/stdc++.h>
using namespace std;
typedef long long ll;

void solve()
{
    int n , l,r;
    l=-1,r=1;
    cin >> n;
    map<int ,int > m;
    while(n--)
    {
        int x ; string s;
        cin >> s >> x;
        if(s=="L")
        {
            m[x]=l;
            l--;
        }
        else if(s=="R")
        {
            m[x]=r;
            r++;
        }
        else
        {
            cout << min(m[x] - l ,r-m[x] )-1 << endl;
        }
    }

}
int main(){
	int t=1;
	//cin >> t;
	while(t--)
		solve();
	return 0;
}


#include <bits/stdc++.h>
using namespace std;
typedef long long ll;

void solve()
{
    ll n , l,r;
    l=0,r=0;
    cin >> n;
    map<int ,int > m;

    while(n--)
    {
        ll x ; char s;
        cin >> s >> x;
        if(l==r)
        {
            m[x]=0;
            l++;
            r--;
        }
        if(s=='L')
        {
            m[x]=l;
            l--;
        }
        else if(s=='R')
        {
            m[x]=r;
            r++;
        }
        else
        {
            cout << min(m[x] - l ,r-m[x] )-1 << endl;
        }
    }

}
int main(){
	int t=1;
	//cin >> t;
	while(t--)
		solve();
	return 0;
}


#include <bits/stdc++.h>
using namespace std;
typedef long long ll;

void solve()
{
    int i , j , k ,r , m, n ,l;
    l=r=0;
    cin >> n ;
    int a[402020];
    while(n--)
    {
        string x;
        ll y;
        cin >> x ;
        cin >> y;
        if(l==r)
        {
            a[y]=0;
            l--;r++;
        }
        else if(x=="R")
        {
            a[y]=r++;
        }
        else if(x=="L")
        {
            a[y]=l--;
        }
        else{
            cout << min(abs(a[y]-l),abs(a[y]-r+1))<< endl;
        }
    }

}
int main(){
	int t=1;
	//cin >> t;
	while(t--)
		solve();
	return 0;
}


#include <bits/stdc++.h>
using namespace std;
typedef long long ll;

void solve()
{
    ll n , l,r;
    l=0,r=0;
    cin >> n;
    map<int ,int > m;

    while(n--)
    {
        ll x ; char s;
        cin >> s >> x;
        if(l==r)
        {
            m[x]=0;
            l++;
            r--;
            continue ;
        }
        if(s=='L')
        {
            m[x]=l;
            l--;
        }
        else if(s=='R')
        {
            m[x]=r;
            r++;
        }
        else
        {
            cout << min(m[x] - l ,r-m[x] )-1 << endl;
        }
    }

}
int main(){
	int t=1;
	//cin >> t;
	while(t--)
		solve();
	return 0;
}


#include <bits/stdc++.h>
using namespace std;
typedef long long ll;

void solve()
{
    ll n , l,r;
    l=-1,r=1;
    cin >> n;
    map<int ,int > m;
    n--;
    while(n--)
    {
        ll x ; char s;
        cin >> s >> x;
        if(s=='L')
        {
            m[x]=l;
            l--;
        }
        else if(s=='R')
        {
            m[x]=r;
            r++;
        }
        else
        {
            cout << min(m[x] - l ,r-m[x] )-1 << endl;
        }
    }

}
int main(){
	int t=1;
	//cin >> t;
	while(t--)
		solve();
	return 0;
}


#include<bits/stdc++.h>
#define ll long long
#define ull unsigned long long
#define ff first
#define ss second
#define pb push_back
#define mk make_pair
#define ld long double
#define y1 asdfghjkl
#define ufo ios_base::sync_with_stdio(false);cin.tie(0);cout.tie(0)
using namespace std;

mt19937_64 mt_rnd_64(chrono::steady_clock::now().time_since_epoch().count());
long long rnd(long long l, long long r){
    return (mt_rnd_64() % (r-l+1)) + l;
}

const int N = 2 * 1e5 + 5;

int n,l,r;
int p[N];
char t;
int id;

main()
{
    ufo;
    cin>>n;
    for(int i = 1;i <= n;i++){
        cin>>t>>id;
        if(t == 'L'){
            l--;
            p[id] = l;
        }
        if(t == 'R'){
            r++;
            p[id] = r;
        }
        if(i == 1)l = r;
        if(t == '?')
            cout<<min( (r - p[id]), (p[id] - l) )<<'\n';
    }
}


#include<bits/stdc++.h>
#define ll long long
#define ull unsigned long long
#define ff first
#define ss second
#define pb push_back
#define mk make_pair
#define ld long double
#define y1 asdfghjkl
#define ufo ios_base::sync_with_stdio(false);cin.tie(0);cout.tie(0)
using namespace std;

mt19937_64 mt_rnd_64(chrono::steady_clock::now().time_since_epoch().count());
long long rnd(long long l, long long r){
    return (mt_rnd_64() % (r-l+1)) + l;
}

const int N = 2 * 1e5 + 5;

int n,l=-1,r=1;
int p[N];
char t;
int id;

main()
{
    ufo;
    cin>>n;
    for(int i = 1;i <= n;i++){
        cin>>t>>id;
        if(t == 'L'){
            l--;
            p[id] = l;
        }
        if(t == 'R'){
            r++;
            p[id] = r;
        }
//        cout<<"!"<<id<<' '<<p[id]<<'\n';
        if(t == '?'){
//            cout<<p[id]<<' '<<l<<' '<<r<<'\n';
            cout<<min( abs(p[id] - r),abs(p[id] - l) )<<'\n';
        }
    }
}


#include<bits/stdc++.h>
#define ll long long
#define ull unsigned long long
#define ff first
#define ss second
#define pb push_back
#define mk make_pair
#define ld long double
#define y1 asdfghjkl
#define ufo ios_base::sync_with_stdio(false);cin.tie(0);cout.tie(0)
using namespace std;

mt19937_64 mt_rnd_64(chrono::steady_clock::now().time_since_epoch().count());
long long rnd(long long l, long long r){
    return (mt_rnd_64() % (r-l+1)) + l;
}

const int N = 1e5 + 5;

int n,l=-1,r=1;
int p[N];
char t;
int id;

main()
{
    ufo;
    cin>>n;
    for(int i = 1;i <= n;i++){
        cin>>t>>id;
        if(t == 'L'){
            l--;
            p[id] = l;
        }
        if(t == 'R'){
            r++;
            p[id] = r;
        }
//        cout<<"!"<<id<<' '<<p[id]<<'\n';
        if(t == '?'){
//            cout<<p[id]<<' '<<l<<' '<<r<<'\n';
            cout<<min( abs(p[id] - r),abs(p[id] - l) )<<'\n';
        }
    }
}


#include<bits/stdc++.h>
#define ll long long
#define ull unsigned long long
#define ff first
#define ss second
#define pb push_back
#define mk make_pair
#define ld long double
#define y1 asdfghjkl
#define ufo ios_base::sync_with_stdio(false);cin.tie(0);cout.tie(0)
using namespace std;

mt19937_64 mt_rnd_64(chrono::steady_clock::now().time_since_epoch().count());
long long rnd(long long l, long long r){
    return (mt_rnd_64() % (r-l+1)) + l;
}

const int N = 2 * 1e5 + 5;

int n,l,r;
int p[N];
char t;
int id;

main()
{
    ufo;
    cin>>n;
    for(int i = 1;i <= n;i++){
        cin>>t>>id;
        if(t == 'L'){
            l--;
            p[id] = l;
        }
        if(t == 'R'){
            r++;
            p[id] = r;
        }
//        cout<<"!"<<id<<' '<<p[id]<<'\n';
        if(t == '?'){
//            cout<<p[id]<<' '<<l<<' '<<r<<'\n';
            cout<<min( abs(p[id] - r),abs(p[id] - l) )<<'\n';
        }
    }
}


#include<bits/stdc++.h>
#define ll long long
#define ull unsigned long long
#define ff first
#define ss second
#define pb push_back
#define mk make_pair
#define ld long double
#define y1 asdfghjkl
#define ufo ios_base::sync_with_stdio(false);cin.tie(0);cout.tie(0)
using namespace std;

mt19937_64 mt_rnd_64(chrono::steady_clock::now().time_since_epoch().count());
long long rnd(long long l, long long r){
    return (mt_rnd_64() % (r-l+1)) + l;
}

const int N = 2 * 1e5 + 5;

int n,l,r;
int p[N];
char t;
int id;

main()
{
    ufo;
    cin>>n;
    for(int i = 1;i <= n;i++){
        cin>>t>>id;
        if(t == 'L'){
            l--;
            if(i == 1)r = l;
            p[id] = l;
        }
        if(t == 'R'){
            r++;
            if(i == 1)l = r;
            p[id] = r;
        }
        if(t == '?'){
//            cout<<"! "<<l<<' '<<p[id]<<' '<<r<<'\n';
            cout<<min( (r - p[id]), (p[id] - l) )<<'\n';
        }
    }
}


#include<bits/stdc++.h>
#define ll long long
#define ull unsigned long long
#define ff first
#define ss second
#define pb push_back
#define mk make_pair
#define ld long double
#define y1 asdfghjkl
#define ufo ios_base::sync_with_stdio(false);cin.tie(0);cout.tie(0)
using namespace std;

mt19937_64 mt_rnd_64(chrono::steady_clock::now().time_since_epoch().count());
long long rnd(long long l, long long r){
    return (mt_rnd_64() % (r-l+1)) + l;
}

const int N = 2 * 1e5 + 5;

int n,l,r;
int p[N];
char t;
int id;

main()
{
    ufo;
    cin>>n;
    for(int i = 1;i <= n;i++){
        cin>>t>>id;
        if(t == 'L'){
            l--;
            p[id] = l;
        }
        if(t == 'R'){
            r++;
            p[id] = r;
        }
        if(t == '?')
            cout<<min( (r - p[id]), (p[id] - l) )<<'\n';
    }
}


#include <stdio.h>

int N;
char str[11];
int id;

int no[200200][4];
int maxno[2]={0, 0};

int main()
{
	int z, k, ansl, ansr;
	scanf("%d", &N);

	for(k=0; k<4; k++)
		for(z=1; z<=N; z++)
			no[z][k]=0;

	while(N--)
	{
		scanf("%s %d", str, &id);

		if( str[0]=='L' )
		{
			maxno[0]++;
			no[id][0]=0;
			no[id][2]=maxno[0];
			no[id][3]=maxno[1];
		}
		else if( str[0]=='R' )
		{
			maxno[1]++;
			no[id][0]=maxno[0]+maxno[1];
			no[id][1]=0;
			no[id][2]=maxno[0];
			no[id][3]=maxno[1];
		}
		else if( str[0]=='?' )
		{
			ansl=maxno[0]-no[id][2]+no[id][0];
			ansr=maxno[1]-no[id][3]+no[id][1];
			printf("%d\n", ansl<ansr?ansl:ansr);
		}
	}

	return 0;
}


#include <stdio.h>

int N;
char str[11];
int id;

int no[200200][4];
int maxno[2]={0, 0};

int main()
{
	int z, k, ansl, ansr;
	scanf("%d", &N);

	for(k=0; k<4; k++)
		for(z=1; z<=N; z++)
			no[z][k]=0;

	while(N--)
	{
		scanf("%s %d", str, &id);

		if( str[0]=='L' )
		{
			maxno[0]++;
			no[id][0]=0;
			no[id][1]=maxno[0]+maxno[1]-1;
			no[id][2]=maxno[0];
			no[id][3]=maxno[1];
		}
		else if( str[0]=='R' )
		{
			maxno[1]++;
			no[id][0]=maxno[0]+maxno[1]-1;
			no[id][1]=0;
			no[id][2]=maxno[0];
			no[id][3]=maxno[1];
		}
		else if( str[0]=='?' )
		{
			ansl=maxno[0]-no[id][2]+no[id][0];
			ansr=maxno[1]-no[id][3]+no[id][1];
			printf("%d\n", ansl<ansr?ansl:ansr);
		}
	}

	return 0;
}


#include <stdio.h>

int N;
char str[11];
int id;

int no[200200][4];
int maxno[2]={0, 0};

int main()
{
	int z, k, ansl, ansr;
	scanf("%d", &N);

	for(k=0; k<4; k++)
		for(z=1; z<=N; z++)
			no[z][k]=0;

	while(N--)
	{
		scanf("%s %d", str, &id);

		if( str[0]=='L' )
		{
			no[id][0]=0;
			no[id][1]=maxno[0]+maxno[1];
			no[id][2]=maxno[0];
			no[id][3]=maxno[1];
			maxno[0]++;
		}
		else if( str[0]=='R' )
		{
			no[id][0]=maxno[0]+maxno[1];
			no[id][1]=0;
			no[id][2]=maxno[0];
			no[id][3]=maxno[1];
			maxno[1]++;
		}
		else if( str[0]=='?' )
		{
			ansl=maxno[0]-no[id][2]+no[id][0];
			ansr=maxno[1]-no[id][3]+no[id][1];
			printf("%d\n", ansl<ansr?ansl:ansr);
		}
	}

	return 0;
}


#include <stdio.h>

int N;
char str[11];
int id;

int no[200200][4];
int maxno[2]={0, 0};

int main()
{
freopen("In.txt", "r", stdin);
	int z, k, ansl, ansr;
	scanf("%d", &N);

	for(k=0; k<4; k++)
		for(z=1; z<=N; z++)
			no[z][k]=0;

	while(N--)
	{
		scanf("%s %d", str, &id);

		if( str[0]=='L' )
		{
			maxno[0]++;
			no[id][0]=0;
			no[id][1]=maxno[0]+maxno[1]-1;
			no[id][2]=maxno[0];
			no[id][3]=maxno[1];
		}
		else if( str[0]=='R' )
		{
			maxno[1]++;
			no[id][0]=maxno[0]+maxno[1]-1;
			no[id][1]=0;
			no[id][2]=maxno[0];
			no[id][3]=maxno[1];
		}
		else if( str[0]=='?' )
		{
			ansl=maxno[0]-no[id][2]+no[id][0];
			ansr=maxno[1]-no[id][3]+no[id][1];
			printf("%d\n", ansl<ansr?ansl:ansr);
		}
	}

	return 0;
}


#include <stdio.h>

int N;
char str[11];
int id;

int no[200200][4];
int maxno[2]={0, 0};

int main()
{
	int z, k, ansl, ansr;
	scanf("%d", &N);

	for(k=0; k<4; k++)
		for(z=1; z<=N; z++)
			no[z][k]=0;

	while(N--)
	{
		scanf("%s %d", str, &id);

		if( str[0]=='L' )
		{
			maxno[0]++;
			no[id][0]=0;
			no[id][1]=maxno[0]+maxno[1];
			no[id][2]=maxno[0];
			no[id][3]=maxno[1];
		}
		else if( str[0]=='R' )
		{
			maxno[1]++;
			no[id][0]=maxno[0]+maxno[1];
			no[id][1]=0;
			no[id][2]=maxno[0];
			no[id][3]=maxno[1];
		}
		else if( str[0]=='?' )
		{
			ansl=maxno[0]-no[id][2]+no[id][0];
			ansr=maxno[1]-no[id][3]+no[id][1];
			printf("%d\n", ansl<ansr?ansl:ansr);
		}
	}

	return 0;
}


#include<bits/stdc++.h>
using namespace std;
typedef long long int ll;
typedef unsigned long long int ull;
#define FastIO  ios_base::sync_with_stdio(false); cin.tie(0);
#define INF     1llu<<61 //2,305,843,009,213,693,952
#define Set(x,y)  memset(x, y, sizeof(x))
#define MAX     301000
int q, id, mid, i=-1, j=-1;
int l[MAX], r[MAX], arr[MAX], ans;
char side;
int main()
{
    FastIO;
    #ifndef ONLINE_JUDGE
        freopen("input.txt", "r", stdin);
    #endif
    cin>>q;
    int flag = 1;
    while(q--){
        cin>>side>>id;
        if(flag){mid = id; flag = 0; continue;}
        if(side=='L'){
            l[id] = ++i;
        }else if(side=='R'){
            r[id] = ++j;
        }else {
            if(mid==id) cout<<min(i+1, j+1)<<endl;
            else {
                if(l[id] > 0){
                    ans = min(i-l[id], (i+j+1)-l[id]);
                    cout<<ans<<endl; continue;
                }else if(r[id] > 0){
                    ans = min(j-r[id], (j-r[id])+i+1);
                    cout<<ans<<endl; continue;
                }
            }
        }
    }
    return 0;
}


#include<bits/stdc++.h>
using namespace std;
typedef long long int ll;
typedef unsigned long long int ull;
#define FastIO      ios_base::sync_with_stdio(false); cin.tie(0);
#define INF         1llu<<61 //2,305,843,009,213,693,952
#define Set(x,y)    memset(x, y, sizeof(x))
#define MAX         201000
int q, id, mid, i=-1, j=-1, ii, jj;
int l[MAX], r[MAX], ans;
char side;
int main()
{
    FastIO;
    #ifndef ONLINE_JUDGE
        freopen("input.txt", "r", stdin);
    #endif
    Set(l, -1); Set(r, -1);
    cin>>q;
    int flag = 1;
    while(q--){
        cin>>side>>id;
        if(flag){mid = id; flag = 0; continue;}
        if(side=='L'){
            l[id] = ++i;
        }else if(side=='R'){
            r[id] = ++j;
        }else {
            if(mid==id) cout<<min(i+1, j+1)<<endl;
            else {
                if(l[id] != -1){
                    if(i==-1) ii = 0; if(j==-1) jj = 0;
                    ans = min(l[id], (ii+jj+2)-l[id]);
                    cout<<ans<<endl; continue;
                }else if(r[id] != -1){
                    if(i==-1) ii = 0; if(j==-1) jj = 0;
                    ans = min(ii+1+r[id], (j-r[id]) );
                    //ans = min(r[id], (j-r[id])+i+1);
                    cout<<ans<<endl; continue;
                }
            }
        }
    }
    return 0;
}


#include<bits/stdc++.h>
using namespace std;
typedef long long int ll;
typedef unsigned long long int ull;
#define FastIO  ios_base::sync_with_stdio(false); cin.tie(0);
#define INF     1llu<<61 //2,305,843,009,213,693,952
#define Set(x,y)  memset(x, y, sizeof(x))
#define MAX     301000
int q, id, mid, i=-1, j=-1;
int l[MAX], r[MAX], arr[MAX], ans;
char side;
int main()
{
    FastIO;
    #ifndef ONLINE_JUDGE
        //freopen("input.txt", "r", stdin);
    #endif
    Set(l, -1); Set(r, -1);
    cin>>q;
    int flag = 1;
    while(q--){
        cin>>side>>id;
        if(flag){mid = id; flag = 0; continue;}
        if(side=='L'){
            l[id] = ++i;
        }else if(side=='R'){
            r[id] = ++j;
        }else {
            if(mid==id) cout<<min(i+1, j+1)<<endl;
            else {
                if(l[id] > -1 && i>-1){
                    ans = min(i-l[id], (i+j+1)-l[id]);
                    cout<<ans<<endl; continue;
                }else if(r[id] > -1 && j>-1){
                    ans = min(j-r[id], (j-r[id])+i+1);
                    cout<<ans<<endl; continue;
                }
            }
        }
    }
    return 0;
}


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

int main()
{
    int n,j=n-1,sum1=0,sum2=0;
    cin>>n
pair<int,int>a[1001];
for(int i=0;i<n;i++)
{
    cin>>a[i].second;
    cin>>a[i].first;
}
sort(a,a+n);
for(int i=0;i<n;i++)
{
    sum1=sum1+a[i].first;
}
while(sum1>=0)
{
    sum2=sum2+a[j].second;
    sum1--;
}
cout<<sum2;
}


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

int main()
{
    int n,j=n-1,sum1=0,sum2=0;
    cin>>n;
pair<int,int>a[1001];
for(int i=0;i<n;i++)
{
    cin>>a[i].second;
    cin>>a[i].first;
}
sort(a,a+n);
for(int i=0;i<n;i++)
{
    sum1=sum1+a[i].first;
}
while(sum1>=0)
{
    sum2=sum2+a[j].second;
    sum1--;
}
cout<<sum2;
}


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

int main()
{
    int n,j=n-1,sum1=0,sum2=0;
    cin>>n
pair<int,int>a[1001];
for(int i=0;i<n;i++)
{
    cin>>a[i].second;
    cin>>a[i].first;
}
sort(a,a+n);
for(int i=0;i<n;i++)
{
    sum1=sum1+a[i].first;
}
while(sum1>=0&&j>=0)
{
    sum2=sum2+a[j].second;
    sum1--;
    j--;
}
cout<<sum2;
}


#include<bits/stdc++.h>
using namespace std;
int main()
{
 int n,sum1=0,sum2=0;
 cin>>n;
  int j=n-1;
pair<int,int>a[1001];
for(int i=0;i<n;i++)
{
    cin>>a[i].second;
    cin>>a[i].first;
}
sort(a,a+n);
for(int i=0;i<n;i++)
{
    sum1=sum1+a[i].first;
}
while(sum1>=0&&j>=0)
{
    sum2=sum2+a[j].second;
    sum1--;
    j--;
}
cout<<sum2;
return 0;
}


#include <iostream>
#include <vector>
#include <cstdlib>
#include <iomanip>
#include <algorithm>
#include <cmath>
#include <set>
#include <map>
#include <fstream>
#include <cstdio>
#include <vector>
#include <cstring>
#include <string>
#include <set>
#include <map>
#include <stack>
#include <queue>
#include <deque>
#include <algorithm>
#include <array>
#include <bitset>
#include <complex>
#include <numeric>
using namespace std;
typedef vector< int > vi;
typedef vector< vi > vvi;
typedef pair< int,int > ii;
#define sz(a) int((a).size())
#define ll long long
#define pb push_back
#define all(c) (c).begin(),(c).end()
#define tr(c,i) for(typeof((c).begin() i = (c).begin(); i != (c).end(); i++)
#define present(c,x) ((c).find(x) != (c).end())
#define cpresent(c,x) (find(all(c),x) != (c).end())
#define input(a,n) for(long long i=0;i<n;i++)cin>>a[i]
#define output(a,n) for(long long i=0;i<n;i++)cout<<a[i]
int main()
{
    ll n;
    cin>>n;
    vector< pair< ll,ll > > v(n);
    for(ll i=0;i<n;i++)
        cin>>v[i].first>>v[i].second;
    ll sum=0,ans=0;
    for(ll i=0;i<n;i++)
        sum+=v[i].second;
    sort(all(v));
    for(ll i=0;i<sum+1;i++)
        ans+=v[n-1-i].first;
    cout<<ans;
}


#include <iostream>
#include <vector>
#include <cstdlib>
#include <iomanip>
#include <algorithm>
#include <cmath>
#include <set>
#include <map>
#include <fstream>
#include <cstdio>
#include <vector>
#include <cstring>
#include <string>
#include <set>
#include <map>
#include <stack>
#include <queue>
#include <deque>
#include <algorithm>
#include <array>
#include <bitset>
#include <complex>
#include <numeric>
using namespace std;
typedef vector< int > vi;
typedef vector< vi > vvi;
typedef pair< int,int > ii;
#define sz(a) int((a).size())
#define ll long long
#define pb push_back
#define all(c) (c).begin(),(c).end()
#define tr(c,i) for(typeof((c).begin() i = (c).begin(); i != (c).end(); i++)
#define present(c,x) ((c).find(x) != (c).end())
#define cpresent(c,x) (find(all(c),x) != (c).end())
#define input(a,n) for(long long i=0;i<n;i++)cin>>a[i]
#define output(a,n) for(long long i=0;i<n;i++)cout<<a[i]
int main()
{
    ll n;
    cin>>n;
    vector< pair< ll,ll > > v(n);
    for(ll i=0;i<n;i++)
        cin>>v[i].first>>v[i].second;
    ll sum=0,ans=0;
    for(ll i=0;i<n;i++)
        sum+=v[i].second;
    sort(all(v));
    for(ll i=0;i<sum+1 && i<n;i++)
        ans+=v[n-1-i].first;
    cout<<ans;
}


#include <iostream>
#include <vector>
#include <cstdlib>
#include <iomanip>
#include <algorithm>
#include <cmath>
#include <set>
#include <map>
#include <fstream>
#include <cstdio>
#include <vector>
#include <cstring>
#include <string>
#include <set>
#include <map>
#include <stack>
#include <queue>
#include <deque>
#include <algorithm>
#include <array>
#include <bitset>
#include <complex>
#include <numeric>
using namespace std;
typedef vector< int > vi;
typedef vector< vi > vvi;
typedef pair< int,int > ii;
#define sz(a) int((a).size())
#define ll long long
#define pb push_back
#define all(c) (c).begin(),(c).end()
#define tr(c,i) for(typeof((c).begin() i = (c).begin(); i != (c).end(); i++)
#define present(c,x) ((c).find(x) != (c).end())
#define cpresent(c,x) (find(all(c),x) != (c).end())
#define input(a,n) for(long long i=0;i<n;i++)cin>>a[i]
#define output(a,n) for(long long i=0;i<n;i++)cout<<a[i]
int main()
{
    ll n;
    cin>>n;
    vector< pair< ll,ll > > v(n);
    for(ll i=0;i<n;i++)
        cin>>v[i].first>>v[i].second;
    ll sum=0,ans=0;
    for(ll i=0;i<n;i++)
        sum+=v[i].second;
    for(ll i=0;i<n;i++)
    {
        if(v[i].second)
        {
            ans+=v[i].first;
            v[i].first=0;
            sum--;
        }
    }
    sort(all(v));
    for(ll i=0;i<sum+1 && i<n;i++)
        ans+=v[n-1-i].first;
    cout<<ans;
}


#include <bits/stdc++.h>
typedef long long ll;
#define get(a) scanf("%lld", &a)
#define repVector(v)  for( auto it = v.begin(); it != v.end(); it++ )
#define all(c) (c).begin(), (c).end()
#define pb push_back
#define FOR(i,a,b) for( ll i = a; i <= b; i++ )
#define ROF(i,a,b) for( ll i = a; i >= b; i-- )
#define debug(x) cerr << "[DEBUG] " << #x << " = " << x << endl
#define matrix vector< vector<ll> >
#define F first
#define S second
#define mp make_pair
#define L 2*r
#define R 2*r+1
#define INPFILE freopen("input.in","r",stdin)
#define BOOST ios_base::sync_with_stdio(false); cin.tie(NULL)
using namespace std;

vector< pair<ll,ll> > a, b;
bool mark[10005] = {0};

int main()
{
    ll n, pick = 1, tot = 0, i;
    cin>>n;
    for(i=0;i<n;i++)
    {
        ll x, y; cin>>x>>y;
        a.pb(mp(x,i)); b.pb(mp(y,i));
    }
    sort(all(a)); sort(all(b));
    for(i=(ll)b.size()-1;i>=0;i--)
    {
        ll idx = b[i].second; ll ncards = b[i].first;
        if(pick+ncards > pick)
        {
            mark[idx] = 1;
            pick += ncards-1;
        }
        else
            break;
    }
    for(i=(ll)a.size()-1;i>=0;i--)
    {
        ll idx = a[i].second; ll npoints = a[i].first;
        if(mark[idx])
            tot += npoints;
        else
        {
            if(pick < 1)
                break;
            tot += npoints;
            pick--;
        }
    }
    cout<<tot<<endl;
    return 0;
}


#include <bits/stdc++.h>
typedef long long ll;
#define get(a) scanf("%lld", &a)
#define repVector(v)  for( auto it = v.begin(); it != v.end(); it++ )
#define all(c) (c).begin(), (c).end()
#define pb push_back
#define FOR(i,a,b) for( ll i = a; i <= b; i++ )
#define ROF(i,a,b) for( ll i = a; i >= b; i-- )
#define debug(x) cerr << "[DEBUG] " << #x << " = " << x << endl
#define matrix vector< vector<ll> >
#define F first
#define S second
#define mp make_pair
#define L 2*r
#define R 2*r+1
#define INPFILE freopen("input.in","r",stdin)
#define BOOST ios_base::sync_with_stdio(false); cin.tie(NULL)
using namespace std;

vector< pair<ll,ll> > a, b;
bool mark[10005] = {0};

int main()
{
    ll n, pick = 1, tot = 0, i, j;
    cin>>n;
    for(i=0;i<n;i++)
    {
        ll x, y; cin>>x>>y;
        a.pb(mp(x,i)); b.pb(mp(y,i));
    }
    sort(all(a)); sort(all(b));
    for(i=(ll)b.size()-1;i>=0;i++)
    {
        ll idx = b[i].second; ll ncards = b[i].first;
        if(pick+ncards > pick)
        {
            mark[idx] = 1;
            pick += ncards-1;
        }
        else
            break;
    }
    for(i=(ll)a.size()-1,j=pick;i>=0 && j>=1;i--)
    {
        ll idx = a[i].second; ll npoints = a[i].first;
        //~ debug(npoints); debug(idx);
        if(mark[idx])
            tot += npoints;
        else
        {
            tot += npoints;
            j--;
        }
        //~ debug(npoints);
    }
    cout<<tot<<endl;
    return 0;
}


#include <bits/stdc++.h>
typedef long long ll;
#define get(a) scanf("%lld", &a)
#define repVector(v)  for( auto it = v.begin(); it != v.end(); it++ )
#define all(c) (c).begin(), (c).end()
#define pb push_back
#define FOR(i,a,b) for( ll i = a; i <= b; i++ )
#define ROF(i,a,b) for( ll i = a; i >= b; i-- )
#define debug(x) cerr << "[DEBUG] " << #x << " = " << x << endl
#define matrix vector< vector<ll> >
#define F first
#define S second
#define mp make_pair
#define L 2*r
#define R 2*r+1
#define INPFILE freopen("input.in","r",stdin)
#define BOOST ios_base::sync_with_stdio(false); cin.tie(NULL)
using namespace std;

vector< pair<ll,ll> > a, b;
bool mark[10005] = {0};

int main()
{
    ll n, pick = 1, tot = 0, i, j;
    cin>>n;
    for(i=0;i<n;i++)
    {
        ll x, y; cin>>x>>y;
        a.pb(mp(x,i)); b.pb(mp(y,i));
    }
    sort(all(a)); sort(all(b));
    for(i=(ll)b.size()-1;i>=0;i--)
    {
        ll idx = b[i].second; ll ncards = b[i].first;
        if(pick+ncards > pick)
        {
            mark[idx] = 1;
            pick += ncards-1;
        }
        else
            break;
    }
    for(i=(ll)a.size()-1,j=pick;i>=0 && j>=1;i--)
    {
        ll idx = a[i].second; ll npoints = a[i].first;
        if(mark[idx])
            tot += npoints;
        else
        {
            tot += npoints;
            j--;
        }
    }
    cout<<tot<<endl;
    return 0;
}


#include <bits/stdc++.h>
typedef long long ll;
#define get(a) scanf("%lld", &a)
#define repVector(v)  for( auto it = v.begin(); it != v.end(); it++ )
#define all(c) (c).begin(), (c).end()
#define pb push_back
#define FOR(i,a,b) for( ll i = a; i <= b; i++ )
#define ROF(i,a,b) for( ll i = a; i >= b; i-- )
#define debug(x) cerr << "[DEBUG] " << #x << " = " << x << endl
#define matrix vector< vector<ll> >
#define F first
#define S second
#define mp make_pair
#define L 2*r
#define R 2*r+1
#define INPFILE freopen("input.in","r",stdin)
#define BOOST ios_base::sync_with_stdio(false); cin.tie(NULL)
using namespace std;

vector< pair<ll,ll> > a, b;
bool mark[10005] = {0};

int main()
{
    ll n, pick = 1, tot = 0, i;
    cin>>n;
    for(i=0;i<n;i++)
    {
        ll x, y; cin>>x>>y;
        a.pb(mp(x,i)); b.pb(mp(y,i));
    }
    sort(all(a)); sort(all(b));
    for(i=(ll)b.size()-1;i>=0;i--)
    {
        ll idx = b[i].second; ll ncards = b[i].first;
        if(pick+ncards > pick)
        {
            mark[idx] = 1;
            pick += ncards-1;
        }
        else
            break;
    }
    for(i=(ll)a.size()-1;i>=0;i--)
    {
        ll idx = a[i].second; ll npoints = a[i].first;
        if(mark[idx])
            tot += npoints;
        else
        {
            if(pick >= 1)
                tot += npoints;
            pick--;
        }
    }
    cout<<tot<<endl;
    return 0;
}


#include <bits/stdc++.h>

using namespace std;

typedef long long int ll;

int main()
{
    int n; cin>>n;
    vector< pair<int,int> >x;
    for(int i=0;i<n;i++){
        int z,y;
        cin>>z>>y;
        x.push_back( pair<int,int>(y,z) );
    }
    sort(x.rbegin(),x.rend());
    int counter=1,sum=0;
    for(int i=0; counter!=0&&i<n ;i++){
        sum+=x[i].second;
        --counter+=x[i].first;
    }
    cout<<sum;

        return 0;
}


#include <bits/stdc++.h>

using namespace std;

typedef long long int ll;

int main()
{
    int n; cin>>n;
    vector< pair<int,int> >x;
    for(int i=0;i<n;i++){
        int z,y;
        cin>>z>>y;
        x.push_back( pair<int,int>(y,z) );
    }
    sort(x.rbegin(),x.rend());
    int counter=1,sum=0;
    for(int i=0; counter!=0 ;i++){
        sum+=x[i].second;
        --counter+=x[i].first;
    }
    cout<<sum;

        return 0;
}


#include <iostream>
#include <iomanip>
#include <vector>
#include <list>
#include <map>
#include <set>
#include <queue>
#include <deque>
#include <stack>
#include <string>
#include <string.h>
#include <math.h>
#include <cmath>
#include <algorithm>
#include <bitset>
#include <functional>
#include <numeric>
#include <utility>
#include <sstream>
#include <cstdio>
#include <cstdlib>
#include <ctime>
#include <sstream>
#include <fstream>
// defines
#define modulo 1000000007
#define pi 3.1415926535897932384
#define Muhammed_Emamm   ios_base::sync_with_stdio(0);cin.tie(0);
#define reset1(m) memset(m, 1 ,sizeof m )
#define reset(m) memset(m , 0 , sizeof m)
#define sf(x) scanf("%d", &x);
#define sfll(x) scanf("%I64d", &x);
#define pr(x) printf("%I64d\n", x);
//type def ...
typedef double d;
typedef long long ll;
typedef unsigned long long ull;

using namespace std;

ll getsumofDigits(ll num)
{
    ll ans = 0 ;
    while(num)
    {
        ans+=num%10 ;
        num/=10 ;
    }
    return ans;
}
ll poww(ll a, ll b)
{
    ll res = 1;
    for(int i = 1; i<=b; ++i)
        res *= a;

    return res;
}

int main ()
{
    Muhammed_Emamm
    ll n , moves = 1, score = 0;
    cin >> n ;
    vector<ll> v , m ;
    for(int i =0 ; i<n ; i++){
        ll x,y ; cin >> x >> y ;
        v.push_back(x) ;
        m.push_back(y) ;
    }
    for(int i = 0 ;i<n ; i++){
        if(m[i]){
            moves+=(m[i]-1) ;
            score+=v[i] ;
            v[i] = 0 ;
        }
    }
    sort(v.begin(),v.end()) ;
    ll inxx = v.size() -1 ;
    while(moves){
        score+=v[inxx] ;
        moves-- ;
        inxx-- ;
    }
    cout << score ;
    return 0 ;
}


#include <iostream>
#include <iomanip>
#include <vector>
#include <list>
#include <map>
#include <set>
#include <queue>
#include <deque>
#include <stack>
#include <string>
#include <string.h>
#include <math.h>
#include <cmath>
#include <algorithm>
#include <bitset>
#include <functional>
#include <numeric>
#include <utility>
#include <sstream>
#include <cstdio>
#include <cstdlib>
#include <ctime>
#include <sstream>
#include <fstream>
// defines
#define modulo 1000000007
#define pi 3.1415926535897932384
#define Muhammed_Emamm   ios_base::sync_with_stdio(0);cin.tie(0);
#define reset1(m) memset(m, 1 ,sizeof m )
#define reset(m) memset(m , 0 , sizeof m)
#define sf(x) scanf("%d", &x);
#define sfll(x) scanf("%I64d", &x);
#define pr(x) printf("%I64d\n", x);
//type def ...
typedef double d;
typedef long long ll;
typedef unsigned long long ull;

using namespace std;

ll getsumofDigits(ll num)
{
    ll ans = 0 ;
    while(num)
    {
        ans+=num%10 ;
        num/=10 ;
    }
    return ans;
}
ll poww(ll a, ll b)
{
    ll res = 1;
    for(int i = 1; i<=b; ++i)
        res *= a;

    return res;
}

int main ()
{
    Muhammed_Emamm
    int n , moves = 1, score = 0;
    cin >> n ;
    vector<int> v , m ;
    for(int i =0 ; i<n ; i++){
        int x,y ; cin >> x >> y ;
        v.push_back(x) ;
        m.push_back(y) ;
    }
    for(int i = 0 ;i<n ; i++){
        if(m[i]){
            moves+=(m[i]-1) ;
            score+=v[i] ;
            v[i] = 0 ;
        }
    }
    sort(v.begin(),v.end()) ;
    int inxx = v.size() -1 ;
    while(moves){
        score+=v[inxx] ;
        moves-- ;
        inxx-- ;
    }
    cout << score ;
    return 0 ;
}


#include <iostream>
#include <iomanip>
#include <vector>
#include <list>
#include <map>
#include <set>
#include <queue>
#include <deque>
#include <stack>
#include <string>
#include <string.h>
#include <math.h>
#include <cmath>
#include <algorithm>
#include <bitset>
#include <functional>
#include <numeric>
#include <utility>
#include <sstream>
#include <cstdio>
#include <cstdlib>
#include <ctime>
#include <sstream>
#include <fstream>
// defines
#define modulo 1000000007
#define pi 3.1415926535897932384
#define Muhammed_Emamm   ios_base::sync_with_stdio(0);cin.tie(0);
#define reset1(m) memset(m, 1 ,sizeof m )
#define reset(m) memset(m , 0 , sizeof m)
#define sf(x) scanf("%d", &x);
#define sfll(x) scanf("%I64d", &x);
#define pr(x) printf("%I64d\n", x);
//type def ...
typedef double d;
typedef long long ll;
typedef unsigned long long ull;

using namespace std;

ll getsumofDigits(ll num)
{
    ll ans = 0 ;
    while(num)
    {
        ans+=num%10 ;
        num/=10 ;
    }
    return ans;
}
ll poww(ll a, ll b)
{
    ll res = 1;
    for(int i = 1; i<=b; ++i)
        res *= a;

    return res;
}

int main ()
{
    Muhammed_Emamm
    ll n , moves = 1, score = 0;
    cin >> n ;
    vector<ll> v , m ;
    for(int i =0 ; i<n ; i++){
        ll x,y ; cin >> x >> y ;
        v.push_back(x) ;
        m.push_back(y) ;
    }
    for(int i = 0 ;i<n ; i++){
        if(m[i]){
            moves+=(m[i]-1) ;
            score+=v[i] ;
            v[i] = 0 ;
        }
    }
    sort(v.begin(),v.end()) ;
    ll inxx = v.size() -1 ;
    while(moves&&inxx){
        score+=v[inxx] ;
        moves-- ;
        inxx-- ;
    }
    cout << score ;
    return 0 ;
}


#include <iostream>
#include <iomanip>
#include <vector>
#include <list>
#include <map>
#include <set>
#include <queue>
#include <deque>
#include <stack>
#include <string>
#include <string.h>
#include <math.h>
#include <cmath>
#include <algorithm>
#include <bitset>
#include <functional>
#include <numeric>
#include <utility>
#include <sstream>
#include <cstdio>
#include <cstdlib>
#include <ctime>
#include <sstream>
#include <fstream>
// defines
#define modulo 1000000007
#define pi 3.1415926535897932384
#define Muhammed_Emamm   ios_base::sync_with_stdio(0);cin.tie(0);
#define reset1(m) memset(m, 1 ,sizeof m )
#define reset(m) memset(m , 0 , sizeof m)
#define sf(x) scanf("%d", &x);
#define sfll(x) scanf("%I64d", &x);
#define pr(x) printf("%I64d\n", x);
//type def ...
typedef double d;
typedef long long ll;
typedef unsigned long long ull;

using namespace std;

ll getsumofDigits(ll num)
{
    ll ans = 0 ;
    while(num)
    {
        ans+=num%10 ;
        num/=10 ;
    }
    return ans;
}
ll poww(ll a, ll b)
{
    ll res = 1;
    for(int i = 1; i<=b; ++i)
        res *= a;

    return res;
}

int main ()
{
    Muhammed_Emamm
    ll n , moves = 1, score = 0;
    cin >> n ;
    vector<ll> v , m ;
    for(int i =0 ; i<n ; i++){
        ll x,y ; cin >> x >> y ;
        v.push_back(x) ;
        m.push_back(y) ;
    }
    for(int i = 0 ;i<n ; i++){
        if(m[i]){
            moves+=(m[i]-1) ;
            score+=v[i] ;
            v[i]= 0 ;
        }
    }
    sort(v.begin(),v.end()) ;
    ll inxx = v.size() -1 ;
    while(moves&&inxx>=0){
        score+=v[inxx] ;
        moves-- ;
        inxx-- ;
    }
    cout << score ;
    return 0 ;
}


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

typedef long long ll;
typedef long double ld;
const ll init = 1e9+7;
const ll N = 1e5+7;

#define mkp make_pair
#define pb push_back
#define pq priority_queue
#define ff first
#define ss second
#define all(a) a.begin(),a.end()
#define sz(a) (ll)(a.size())
#define minpq priority_queue <int, vector<int>, greater<int> >
#define vi vector <int>
#define vll vector <ll>
#define pii pair<int,int>

int main()
{
	ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0);
	int n; cin>>n;
	int cnt=0;
	vi v0,v1;
	for(int i=0;i<n;++i){
		int a,b; cin>>a>>b;
		if(b==0) {
			v0.pb(-a);
		}
		else{
			v1.pb(-a);
			cnt += b;
		}
	}

	sort(all(v0));
	sort(all(v1));

	for(int i=0;i<v0.size();++i) v0[i] *= (-1);
	for(int i=0;i<v1.size();++i) v1[i] *= (-1);

	int ans=0;
	if(v0.size()==n) ans = v0[0];
	else{
		if(cnt>=n){
			for(int i=0;i<v0.size();++i) ans += v0[i];
			for(int i=0;i<v0.size();++i) ans += v1[i];
		}
		else{
			for(int i=0;i<v0.size();++i) ans += v0[i];
			for(int i=0;i<cnt && i<v1.size();++i) ans += v1[i];
		}
	}
	cout<<ans<<endl;
    return 0;
}


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

typedef long long ll;
typedef long double ld;
const ll init = 1e9+7;
const ll N = 1e5+7;

#define mkp make_pair
#define pb push_back
#define pq priority_queue
#define ff first
#define ss second
#define all(a) a.begin(),a.end()
#define sz(a) (ll)(a.size())
#define minpq priority_queue <int, vector<int>, greater<int> >
#define vi vector <int>
#define vll vector <ll>
#define pii pair<int,int>

int main()
{
	ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0);
	int n; cin>>n;
	int cnt=0;
	vi v0,v1;
	for(int i=0;i<n;++i){
		int a,b; cin>>a>>b;
		if(b==0) {
			v0.pb(-a);
		}
		else{
			v1.pb(-a);
			cnt += b;
		}
	}

	sort(all(v0));
	sort(all(v1));

	for(int i=0;i<v0.size();++i) v0[i] *= (-1);
	for(int i=0;i<v1.size();++i) v1[i] *= (-1);

	int ans=0;
	if(v0.size()==n) ans = v0[0];
	else{
		if(cnt>=n){
			for(int i=0;i<v0.size();++i) ans += v0[i];
			for(int i=0;i<v0.size();++i) ans += v1[i];
		}
		else{
			for(int i=0;i<v0.size();++i) ans += v1[i];
			for(int i=0;i<cnt && i<v1.size();++i) ans += v0[i];
		}
	}
	cout<<ans<<endl;
    return 0;
}


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

typedef long long ll;
typedef long double ld;
const ll init = 1e9+7;
const ll N = 1e5+7;

#define mkp make_pair
#define pb push_back
#define pq priority_queue
#define ff first
#define ss second
#define all(a) a.begin(),a.end()
#define sz(a) (ll)(a.size())
#define minpq priority_queue <int, vector<int>, greater<int> >
#define vi vector <int>
#define vll vector <ll>
#define pii pair<int,int>

int main()
{
	ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0);
	int n; cin>>n;
	int cnt=0;
	vi v0,v1;
	for(int i=0;i<n;++i){
		int a,b; cin>>a>>b;
		if(b==0) {
			v0.pb(-a);
		}
		else{
			v1.pb(-a);
			cnt += b;
		}
	}

	sort(all(v0));
	sort(all(v1));

	for(int i=0;i<v0.size();++i) v0[i] *= (-1);
	for(int i=0;i<v1.size();++i) v1[i] *= (-1);

	int ans=0;
	if(v0.size()==n) ans = v0[0];
	else{
		if(cnt>=n){
			for(int i=0;i<v0.size();++i) ans += v0[i];
			for(int i=0;i<v1.size();++i) ans += v1[i];
		}
		else{
			for(int i=0;i<v1.size();++i) ans += v1[i];
			for(int i=0;i<cnt && i<v0.size();++i) ans += v0[i];
		}
	}
	cout<<ans<<endl;
    return 0;
}


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

typedef long long ll;
typedef long double ld;
const ll init = 1e9+7;
const ll N = 1e5+7;

#define mkp make_pair
#define pb push_back
#define pq priority_queue
#define ff first
#define ss second
#define all(a) a.begin(),a.end()
#define sz(a) (ll)(a.size())
#define minpq priority_queue <int, vector<int>, greater<int> >
#define vi vector <int>
#define vll vector <ll>
#define pii pair<int,int>

int main()
{
	ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0);
	int n; cin>>n;
	int cnt=0;
	vi v0,v1;
	for(int i=0;i<n;++i){
		int a,b; cin>>a>>b;
		if(b==0) {
			v0.pb(-a);
		}
		else{
			if(v1.size()>0) b--;
			v1.pb(-a);
			cnt += b;
		}
	}

	sort(all(v0));
	sort(all(v1));

	for(int i=0;i<v0.size();++i) v0[i] *= (-1);
	for(int i=0;i<v1.size();++i) v1[i] *= (-1);

	int ans=0;
	if(v0.size()==n) ans = v0[0];
	else{
		if(cnt>=n){
			for(int i=0;i<v0.size();++i) ans += v0[i];
			for(int i=0;i<v1.size();++i) ans += v1[i];
		}
		else{
			for(int i=0;i<v1.size();++i) ans += v1[i];
			for(int i=0;i<cnt && i<v0.size();++i) ans += v0[i];
		}
	}
	cout<<ans<<endl;
    return 0;
}


/**
	* Author   : Muhammad Tawsif Sazid
	* Military Institute and Science and Technology
	*
	*
**/

#include <bits/stdc++.h>
#define pii acos(-1)
#define ll long long
#define pare pair<int,int>
#define eps 1e-9
#define max 60006
#define read(type) readInt<type>()

/****** Template of some basic operations *****/

template<typename T, typename U> inline void amin(T &x, U y) { if(y < x) x = y; }
template<typename T, typename U> inline void amax(T &x, U y) { if(x < y) x = y; }

/**********************************************/

using namespace std;

///dir array for Queen int dxq[10] = {-1,-1,-1,1,1,1,0,0};
///dir array for Queen int dyq[10] = {-1,0,1,-1,0,1,-1,1};
///dir array for knight int dxk[10] = {-2,-2,-1,-1,1,1,2,2};
///dir array for knight int dyk[10] = {1,-1,-2,2,-2,2,-1,1};

/*int leap(int year){
   	if( year%4 == 0 && year%100 == !0 )
            return 1;
	else if (year%100 == 0 && year%400 == 0)
            return 1;
	else
        return 0;
      while(ct > 0){
        double  r = ((double) rand() / (RAND_MAX));
        cout<<r<<endl;
        ct--;
    }
}*/

int cases,ct = 10;

int main(){
    //freopen("input.txt","r",stdin);
    //freopen("output.txt","w",stdout);
    int i,j,k,n,a,b,total = 0,res = 0;
    while(cin>>n){
        vector<int>yoo;
        for(i = 0 ; i<n ; i++){
            cin>>a>>b;
            if(b){
                total = total + b;
                ///total--;
                res = res + a;
            }
            yoo.push_back(a);
        }
         sort(yoo.begin(),yoo.end());
        reverse(yoo.begin(),yoo.end());
        if(total){
            int index = 0;
            while(total--){
                res = res + yoo[index];
                index++;
            }
            cout<<res<<endl;
        }
        else{
            cout<<yoo[0]<<endl;
        }
        //if()
    }
}


/**
	* Author   : Muhammad Tawsif Sazid
	* Military Institute and Science and Technology
	*
	*
**/

#include <bits/stdc++.h>
#define pii acos(-1)
#define ll long long
#define pare pair<int,int>
#define eps 1e-9
#define max 60006
#define read(type) readInt<type>()

/****** Template of some basic operations *****/

template<typename T, typename U> inline void amin(T &x, U y) { if(y < x) x = y; }
template<typename T, typename U> inline void amax(T &x, U y) { if(x < y) x = y; }

/**********************************************/

using namespace std;

///dir array for Queen int dxq[10] = {-1,-1,-1,1,1,1,0,0};
///dir array for Queen int dyq[10] = {-1,0,1,-1,0,1,-1,1};
///dir array for knight int dxk[10] = {-2,-2,-1,-1,1,1,2,2};
///dir array for knight int dyk[10] = {1,-1,-2,2,-2,2,-1,1};

/*int leap(int year){
   	if( year%4 == 0 && year%100 == !0 )
            return 1;
	else if (year%100 == 0 && year%400 == 0)
            return 1;
	else
        return 0;
      while(ct > 0){
        double  r = ((double) rand() / (RAND_MAX));
        cout<<r<<endl;
        ct--;
    }
}*/

int cases,ct = 10;

int main(){
    //freopen("input.txt","r",stdin);
    //freopen("output.txt","w",stdout);
    int i,j,k,n,a,b,total = 1,res = 0;
    while(cin>>n){
        vector<int>yoo;
        for(i = 0 ; i<n ; i++){
            cin>>a>>b;
            if(b){
                total = total + b;
                total--;
                res = res + a;

            }
            else yoo.push_back(a);
        }
         sort(yoo.begin(),yoo.end());
        reverse(yoo.begin(),yoo.end());
        //for(i=0;i<yoo.size();i++){
        //    cout<<yoo[i]<<endl;
        //}
        if(total){
            for(i=0;i<yoo.size();i++){
                if(total == 0)break;
                res = res + yoo[i];
                total--;
            }
            cout<<res<<endl;
        }
        else{
            cout<<yoo[0]<<endl;
        }
        //if()
    }
}


/**
	* Author   : Muhammad Tawsif Sazid
	* Military Institute and Science and Technology
	*
	*
**/

#include <bits/stdc++.h>
#define pii acos(-1)
#define ll long long
#define pare pair<int,int>
#define eps 1e-9
#define max 60006
#define read(type) readInt<type>()

/****** Template of some basic operations *****/

template<typename T, typename U> inline void amin(T &x, U y) { if(y < x) x = y; }
template<typename T, typename U> inline void amax(T &x, U y) { if(x < y) x = y; }

/**********************************************/

using namespace std;

///dir array for Queen int dxq[10] = {-1,-1,-1,1,1,1,0,0};
///dir array for Queen int dyq[10] = {-1,0,1,-1,0,1,-1,1};
///dir array for knight int dxk[10] = {-2,-2,-1,-1,1,1,2,2};
///dir array for knight int dyk[10] = {1,-1,-2,2,-2,2,-1,1};

/*int leap(int year){
   	if( year%4 == 0 && year%100 == !0 )
            return 1;
	else if (year%100 == 0 && year%400 == 0)
            return 1;
	else
        return 0;
      while(ct > 0){
        double  r = ((double) rand() / (RAND_MAX));
        cout<<r<<endl;
        ct--;
    }
}*/

int cases,ct = 10;

int main(){
    //freopen("input.txt","r",stdin);
    //freopen("output.txt","w",stdout);
    int i,j,k,n,a,b,total = 0,res = 0;
    while(cin>>n){
        vector<int>yoo;
        for(i = 0 ; i<n ; i++){
            cin>>a>>b;
            if(b){
                total = total + b;
                ///total--;
                res = res + a;
            }
            else yoo.push_back(a);
        }
         sort(yoo.begin(),yoo.end());
        reverse(yoo.begin(),yoo.end());
        if(total){
            int index = 0;
            while(total--){
                res = res + yoo[index];
                index++;
            }
            cout<<res<<endl;
        }
        else{
            cout<<yoo[0]<<endl;
        }
        //if()
    }
}


/**
	* Author   : Muhammad Tawsif Sazid
	* Military Institute and Science and Technology
	*
	*
**/

#include <bits/stdc++.h>
#define pii acos(-1)
#define ll long long
#define pare pair<int,int>
#define eps 1e-9
#define max 60006
#define read(type) readInt<type>()

/****** Template of some basic operations *****/

template<typename T, typename U> inline void amin(T &x, U y) { if(y < x) x = y; }
template<typename T, typename U> inline void amax(T &x, U y) { if(x < y) x = y; }

/**********************************************/

using namespace std;

///dir array for Queen int dxq[10] = {-1,-1,-1,1,1,1,0,0};
///dir array for Queen int dyq[10] = {-1,0,1,-1,0,1,-1,1};
///dir array for knight int dxk[10] = {-2,-2,-1,-1,1,1,2,2};
///dir array for knight int dyk[10] = {1,-1,-2,2,-2,2,-1,1};

/*int leap(int year){
   	if( year%4 == 0 && year%100 == !0 )
            return 1;
	else if (year%100 == 0 && year%400 == 0)
            return 1;
	else
        return 0;
      while(ct > 0){
        double  r = ((double) rand() / (RAND_MAX));
        cout<<r<<endl;
        ct--;
    }
}*/

int cases,ct = 10;

int main(){
    //freopen("input.txt","r",stdin);
    //freopen("output.txt","w",stdout);
    int i,j,k,n,a,b,total = 1,res = 0;
    while(cin>>n){
        vector<int>yoo;
        for(i = 0 ; i<n ; i++){
            cin>>a>>b;
            if(b){
                total = total + b;
                total--;
                res = res + a;

            }
            else yoo.push_back(a);
        }
         sort(yoo.begin(),yoo.end());
        reverse(yoo.begin(),yoo.end());
        //for(i=0;i<yoo.size();i++){
        //    cout<<yoo[i]<<endl;
        //}
        if(total){
            int index = 0;
            while(total--){
                res = res + yoo[index];
                index++;
            }
            cout<<res<<endl;
        }
        else{
            cout<<yoo[0]<<endl;
        }
        //if()
    }
}


#include<bits/stdc++.h>
using namespace std;
int main()
{int n,i;
cin>>n;
pair<int , int>a[1001];
int c=0,d=1;

for(i=0;i<n;i++)
   cin>>a[i].second>>a[i].first;
   sort(a,a+n);
   reverse(a,a+n);
//    cout<<a[i].second<<a[i].first;
for(i=0;i<n;i++)
    {
        c+=a[i].second;
        d+=a[i].first;
        d--;
        if(d==0) break;
    }cout<<c;
}


#include<bits/stdc++.h>
using namespace std;
int main()
{int n;
cin>>n;
int a[n],b[n],i,j=0,k=0,l,m;

for(i=0;i<n;i++)
   {
    cin>>a[i]>>b[i];
    if(k<=a[i])
        k=a[i],m=i;
    if(j<=b[i])
        j=b[i],l=i;}
    if(j!=0)
        cout<<l+1;
    else
        cout<<m+1;}


#include<iostream>
#include<string>
#include<vector>
#include<algorithm>
using namespace std;
bool sortbysec(const pair<long long int,long long int> &a,const pair<long long int,long long int> &b)
{
    if(a.second < b.second)
    	return 1;
    if(a.second == b.second)
    {
    	if(a.first > b.first)
    		return 0;
    	else
    		return 1;
    }
    if(a.second > b.second)
    	return 0;
}
int main()
{
	long long int n=0,temp1=0,temp2=0,max1=0;
	cin>>n;
    long long int max2=0;
    long long int d=0;
    vector < pair<long long int, long long int > > v1;
	for (int i = 0; i < n; ++i)
	{
		cin>>temp1>>temp2;
		v1.push_back( make_pair(temp1,temp2));
		if(max2 < temp1)
			max2 = temp1;
	}
	temp2=0;
	temp1=0;
	sort(v1.begin(), v1.end(),sortbysec);
	temp2 = v1[n-1].second;
	temp1 = v1[n-1].first;
	if(temp2 > 0)
	{
		while(temp2 > 0 && n-d-2 >= 0 && temp2 < n)
		{
			temp1 = temp1 + v1[n-d-2].first;
			temp2 = temp2 + v1[n-d-2].second;
			temp2--;
			d++;
		}
	}
	if(temp1 > max2)
		cout<<temp1<<endl;
	else
		cout<<max2<<endl;
	return 0;
}


#include<iostream>
#include<string>
#include<vector>
#include<algorithm>
#include<cstdio>
using namespace std;
bool sortbysec(const pair<long long int,long long int> &a,const pair<long long int,long long int> &b)
{
    if(a.second < b.second)
    	return 0;
    if(a.second == b.second)
    {
    	if(a.first > b.first)
    		return 1;
    	else
    		return 0;
    }
    if(a.second > b.second)
    	return 1;
}
int main()
{
	long long int n=0,temp1=0,temp2=0;
	cin >> n;
	long long int max=0;
	vector<std::pair<long long int,long long int> >v1;
	for(long long int i=0;i<n;i++)
	{
		cin >> temp1 >> temp2;
		v1.push_back(make_pair(temp1,temp2));
		if(temp1 >= max)
			max = temp1;
	}
	temp1=0;
	temp2=0;
	sort(v1.begin(),v1.end(),sortbysec);
	temp1 = temp1 + v1[0].second;
	temp2 = temp2+ v1[0].first;
	for(long long int i=1; i < n;i++)
	{
		if(temp1 > 0)
		{
			temp1 = temp1 + (v1[i].second)- 1;
			temp2 = temp2 + (v1[i].first);
		}
	}
	cout<<temp2<<endl;
	return 0;
}


#include<iostream>
#include<string>
#include<vector>
#include<algorithm>
using namespace std;
bool sortbysec(const pair<int,int> &a,const pair<int,int> &b)
{
    if(a.second < b.second)
    	return 1;
    if(a.second == b.second)
    {
    	if(a.first > b.first)
    		return 0;
    	else
    		return 1;
    }
    if(a.second > b.second)
    	return 0;
}
int main()
{
	long long int n=0,temp1=0,temp2=0,max1=0;
	cin>>n;
    long long int max2=0;
    long long int d=0;
    vector < pair<long long int, long long int > > v1;
	for (int i = 0; i < n; ++i)
	{
		cin>>temp1>>temp2;
		v1.push_back( make_pair(temp1,temp2));
		if(max2 < temp1)
			max2 = temp1;
	}
	temp2=0;
	temp1=0;
	sort(v1.begin(), v1.end(),sortbysec);
	temp2 = v1[n-1].second;
	temp1 = v1[n-1].first;
	if(temp2 > 0)
	{
		while(temp2 > 0 && n-d-2 >= 0)
		{
			temp1 = temp1 + v1[n-d-2].first;
			temp2 = temp2 + v1[n-d-2].second;
			temp2--;
			d++;
		}
	}
	if(temp1 > max2)
		cout<<temp1<<endl;
	else
		cout<<max2<<endl;
	return 0;
}


#include<iostream>
#include<string>
#include<vector>
#include<algorithm>
#include<cstdio>
using namespace std;
bool sortbysec(const pair<long long int,long long int> &a,const pair<long long int,long long int> &b)
{
    if(a.second < b.second)
    	return 1;
    if(a.second == b.second)
    {
    	if(a.first > b.first)
    		return 0;
    	else
    		return 1;
    }
    if(a.second > b.second)
    	return 0;
}
int main()
{
	long long int n=0,temp1=0,temp2=0,max1=0;
	cin>>n;
    long long int max2=0;
    long long int d=0;
    vector < pair<long long int, long long int > > v1;
	for (long long int i = 0; i < n; ++i)
	{
		scanf("%l64d %l64d",&temp1,&temp2);
		v1.push_back( make_pair(temp1,temp2));
		if(max2 < temp1)
			max2 = temp1;
	}
	temp2=0;
	temp1=0;
	// sort(v1.begin(), v1.end(),sortbysec);
	temp2 = v1[n-1].second;
	temp1 = v1[n-1].first;
	if(temp2 > 0)
	{
		while(temp2 > 0 && n-d-2 >= 0)
		{
			temp1 = temp1 + v1[n-d-2].first;
			temp2 = temp2 + v1[n-d-2].second;
			temp2--;
			d++;
		}
	}
	if(temp1 > max2)
		cout<<temp1<<endl;
	else
		cout<<max2<<endl;
	return 0;
}


#include<iostream>
#include<string>
#include<vector>
#include<algorithm>
#include<cstdio>
using namespace std;
bool sortbysec(const pair<long long int,long long int> &a,const pair<long long int,long long int> &b)
{
    if(a.second < b.second)
    	return 1;
    if(a.second == b.second)
    {
    	if(a.first > b.first)
    		return 0;
    	else
    		return 1;
    }
    if(a.second > b.second)
    	return 0;
}
int main()
{
	long long int n=0,temp1=0,temp2=0,max1=0;
	cin>>n;
    long long int max2=0;
    long long int d=0;
    vector < pair<long long int, long long int > > v1;
	for (long long int i = 0; i < n; ++i)
	{
		scanf("%l64d %l64d",&temp1,&temp2);
		v1.push_back( make_pair(temp1,temp2));
		if(max2 < temp1)
			max2 = temp1;
	}
	temp2=0;
	temp1=0;
	sort(v1.begin(), v1.end(),sortbysec);
	temp2 = v1[n-1].second;
	temp1 = v1[n-1].first;
	if(temp2 > 0)
	{
		while(temp2 > 0 && n-d-2 >= 0)
		{
			temp1 = temp1 + v1[n-d-2].first;
			temp2 = temp2 + v1[n-d-2].second;
			temp2--;
			d++;
		}
	}
	if(temp1 > max2)
		cout<<temp1<<endl;
	else
		cout<<max2<<endl;
	return 0;
}


#include<iostream>
#include<string>
#include<vector>
#include<algorithm>
using namespace std;
bool sortbysec(const pair<int,int> &a,const pair<int,int> &b)
{
    if(a.second < b.second)
    	return 1;
    if(a.second == b.second)
    {
    	if(a.first > b.first)
    		return 0;
    	else
    		return 1;
    }
    if(a.second > b.second)
    	return 0;
}
int main()
{
	long long int n=0,temp1=0,temp2=0,max1=0;
	cin>>n;
    long long int max2=0;
    long long int d=0;
    vector < pair<long long int, long long int > > v1;
	for (int i = 0; i < n; ++i)
	{
		cin>>temp1>>temp2;
		v1.push_back( make_pair(temp1,temp2));
		if(max2 < temp1)
			max2 = temp1;
	}
	temp2=0;
	temp1=0;
	sort(v1.begin(), v1.end(),sortbysec);
	temp2 = v1[n-1].second;
	temp1 = v1[n-1].first;
	if(temp2 > 0)
	{
		while(temp2 > 0 && temp2 < n)
		{
			temp1 = temp1 + v1[n-d-2].first;
			temp2 = temp2 + v1[n-d-2].second;
			temp2--;
			d++;
		}
	}
	if(temp1 > max2)
		cout<<temp1<<endl;
	else
		cout<<max2<<endl;
	return 0;
}


#include<bits/stdc++.h>
#define ios_base::sync_with_stdio(false);cin.tie(NULL);
using namespace std;
int main()
{
    int n,points=0,counter=1;
    scanf("%d",&n);
    pair<int,int>p[10050];
    for(int i=0; i<n; i++)
       cin>>p[i].second>>p[i].first;
  sort(p,p+n);
   for(int i=n-1; i>=0&&counter>0; i--)
    {
      points+=p[i].second,counter--;
      counter+=p[i].first;
    }
    printf("%d",points);
    return 0;
}


#include<bits/stdc++.h>
#define ios_base::sync_with_stdio(false);cin.tie(NULL);
using namespace std;
int main()
{
    int n,points=0,counter=1;
    scanf("%d",&n);
    pair<int,int>p[10050];
    for(int i=0; i<n; i++)
       cin>>p[i].second>>p[i].first;
  sort(p,p+n);  cout<<endl;
   for(int i=n-1; i>=0&&counter>0; i--)
    {
      points+=p[i].second,counter--;
      counter+=p[i].first;
    }
    printf("%d",points);
    return 0;
}


#include<bits/stdc++.h>
#define ios_base::sync_with_stdio(false);cin.tie(NULL);
using namespace std;
int main()
{
    int n,x,y,points=0,counter=1,mxB=0,mxA=0,indB=0,indA=0;
    vector<int>a; vector<int>b;
    scanf("%d",&n);
    for(int i=0; i<n; i++)
    {
      scanf("%d %d",&x,&y),a.push_back(x),b.push_back(y);
      if(x>mxA)mxA=x,indA=i;
      if(y>mxB)mxB=y,indB=i;
    }
    if(mxB>0)counter--,counter+=mxB,points+=a[indB],a.erase(a.begin()+indB),b.erase(b.begin()+indB);
    else if(mxA>0)counter--,counter+=b[indA],points+=mxA,a.erase(a.begin()+indA),b.erase(b.begin()+indA);
    if(counter>0){
      while(counter>0)
      {mxB=0,mxA=0,indB=0,indA=0;
        for(int j=0; j<b.size(); j++)
         {
            if(b[j]>mxB)mxB=b[j],indB=j;
         }
        if(mxB>0)counter--,counter+=mxB,points+=a[indB],a.erase(a.begin()+indB),b.erase(b.begin()+indB);
        else{
         for(int j=0; j<a.size(); j++)
          {
            if(a[j]>mxA)mxA=a[j],indA=j;
          }
          if(mxA>0)counter--,counter+=b[indA],points+=a[indA],a.erase(a.begin()+indA),b.erase(b.begin()+indA);
        }
      }
    }
    printf("%d",points);
    return 0;
}


#include<bits/stdc++.h>
#define ios_base::sync_with_stdio(false);cin.tie(NULL);
using namespace std;
int main()
{
    int n,x,y,points=0,counter=1,mxB=0,mxA=0,indB=0,indA=0;
    vector<int>a; vector<int>b;
    scanf("%d",&n);
    for(int i=0; i<n; i++)
    {
      scanf("%d %d",&x,&y),a.push_back(x),b.push_back(y);
      if(x>mxA)mxA=x,indA=i;
      if(y>mxB)mxB=y,indB=i;
    }
    if(mxB>0)counter--,counter+=mxB,points+=a[indB],a.erase(a.begin()+indB),b.erase(b.begin()+indB);
    else if(mxA>0)counter--,counter+=b[indA],points+=mxA,a.erase(a.begin()+indA),b.erase(b.begin()+indA);
    if(counter>0 &&a.size()>0 &&b.size()>0){
      while(counter>0)
      {mxB=0,mxA=0,indB=0,indA=0;
        for(int j=0; j<b.size(); j++)
         {
            if(b[j]>mxB)mxB=b[j],indB=j;
         }
        if(mxB>0)counter--,counter+=mxB,points+=a[indB],a.erase(a.begin()+indB),b.erase(b.begin()+indB);
        else{
         for(int j=0; j<a.size(); j++)
          {
            if(a[j]>mxA)mxA=a[j],indA=j;
          }
          if(mxA>0)counter--,counter+=b[indA],points+=a[indA],a.erase(a.begin()+indA),b.erase(b.begin()+indA);
        }
      }
    }
    printf("%d",points);
    return 0;
}


#include<bits/stdc++.h>
#define ios_base::sync_with_stdio(false);cin.tie(NULL);
using namespace std;
int main()
{
    int n,x,y,c=0,mx=0,ind=0,siz=1,points=0,mx2=0,ind2=0;
    vector<int>a; vector<int>b;
    scanf("%d",&n);
    for(int i=0; i<n; i++)
    {
      scanf("%d %d",&x,&y),a.push_back(x),b.push_back(y);
      if(y>mx)  mx=y, ind=i;
      if(x>mx2) mx2=x,ind2=i;
    }
    while(true)
    {
       if(mx>0)c++,siz--,siz+=mx,mx=0,a.erase(a.begin()+ind),b.erase(b.begin()+ind);
       else
       {
        if(c==0)
         points+=mx2,siz--,siz+=b[ind],a.erase(a.begin()+ind2),b.erase(b.begin()+ind2);
        else{
            for(int i=0; i<siz; i++)
            {
                points+=a[i],siz--,siz+=b[i],a.erase(a.begin()+i),b.erase(b.begin()+i);
            }
        }
       }
       if(siz==0 || a.size()==0) break;
    }
    printf("%d",points);
    return 0;
}


#include<bits/stdc++.h>
using namespace std;
int main()
{
    int n,in[1000],a,b,k=0,i;
    long long sum=0;
    int mv=0;
    cin >> n;
    for(i=0; i<n; i++)
    {
        cin >> a >> b;
        if(b>0)
        {
            mv+=b;
            sum+=a;
        }
        else
        {
            in[k++]=a;
        }
    }
    if(mv==0) mv=1;
    sort(in,in+k);
    for(i=0; i<mv; i++)
    {
        if(k==0) break;
        sum+=in[--k];
    }
    cout << sum;
    return 0;
}


#include<bits/stdc++.h>
using namespace std;
int main()
{
    int n,in[1000],a,b,k=0,i;
    long long sum=0;
    int mv=0;
    cin >> n;
    int f=1;
    for(i=0; i<n; i++)
    {
        cin >> a >> b;
        if(b>0)
        {
            mv+=b;
            sum+=a;
            if(f==1) f=0;
            else mv--;
        }
        else
        {
            in[k++]=a;
        }
    }
    if(mv==0) mv=1;
    sort(in,in+k);
    for(i=0; i<mv; i++)
    {
        if(k==0) break;

        sum+=in[--k];
    }
    cout << sum;
    return 0;
}


#include<bits/stdc++.h>
using namespace std;
int main()
{
    int n,in[1000],a,b,k=0,i;
    long long sum=0;
    int mv=0;
    cin >> n;
    for(i=0; i<n; i++)
    {
        cin >> a >> b;
        if(b>0)
        {
            mv+=b;
            sum+=a;
        }
        else
        {
            in[k++]=a;
        }
    }
    if(mv==0) mv=1;
    sort(in,in+k);
    for(i=0; i<mv; i++)
    {
        sum+=in[--k];
    }
    cout << sum;
    return 0;
}


#include<bits/stdc++.h>
using namespace std;
int main()
{
    int sum=0,n,i,a,b,k;
    int in[1005];
    cin >> n;
    int mx=0,mxz=-1;
    for(i=0; i<n; i++)
    {
        cin >> a >> b;
        in[i]=a;
        if(b>=mx)
        {
            if(b==mx)
            {
                if(sum<b)
                {
                    sum=b;
                }
            }
            else
            {
                sum=b;
            }
            mx=b;
        }
        if(a>mxz) mxz=a;
    }
    int save=sum;
    sort(in,in+n);
    k=n-1;
    int ck=1;
    if(mx==0) sum=mxz;
    for(i=0; i<mx; i++)
    {
        if(ck==1 && in[k--]==save)
        {
            ck=0;
            i--;
        }
        else
        {
            sum+=in[k--];
        }
    }
    cout << sum;
    return 0;
}


#include <iostream>
#include <cstdio>
#include <string.h>
#include <algorithm>
using namespace std;

int ans = 0;
int n;
pair<int, int> a[100500];

int main() {
    scanf("%d", &n);
    for(int i = 0; i < n; i++) {
            scanf("%d %d", &a[i].first, &a[i].second);
    }

    int lf = 1;

    for(int i = 0; i < n; i++) {
            if (a[i].second != 0) {
                     ans += a[i].first;
                     lf += a[i].second - 1;
            }
    }

    sort(a, a + n);

    for(int i = n - 1; i >= 0; i--) {
            if (a[i].second == 0 && lf > 0) {
                            lf--;
                            ans += a[i].first;
            }
    }

    printf("%d", ans);

    return 0;
}


#include <iostream>
#include <cstdio>
#include <string.h>
#include <algorithm>
using namespace std;

int ans = 0;
int n;
pair<int, int> a[100500];

int main() {
    scanf("%d", &n);
    for(int i = 0; i < n; i++) {
            scanf("%d %d", &a[i].first, &a[i].second);
    }

    int lf = 0;

    for(int i = 0; i < n; i++) {
            if (a[i].second != 0) {
                     ans += a[i].first;
                     lf += a[i].second - 1;
            }
    }

    sort(a, a + n);

    for(int i = n - 1; i >= 0; i--) {
            if (a[i].second == 0 && lf > 0) {
                            lf--;
                            ans += a[i].first;
            }
    }

    printf("%d", ans);

    return 0;
}


#include <iostream>
#include <cstdio>
#include <string.h>
using namespace std;

int ans = 0;
int n;
pair<int, int> a[100500];

int main() {
    scanf("%d", &n);
    for(int i = 0; i < n; i++) {
            scanf("%d %d", &a[i].first, &a[i].second);
    }

    int lf = 0;

    for(int i = 0; i < n; i++) {
            if (a[i].second != 0) {
                     ans += a[i].first;
                     lf += a[i].second - 1;
            }
    }

    sort(a, a + n);

    for(int i = n - 1; i >= 0; i--) {
            if (a[i].second == 0 && lf > 0) {
                            lf--;
                            ans += a[i].first;
            }
    }

    printf("%d", ans);

    return 0;
}


#include <iostream>
#include <cstdio>
#include <string.h>
#include <algorithm>
using namespace std;

int ans = 0;
int n;
pair<int, int> a[100500];

int main() {
    scanf("%d", &n);
    for(int i = 0; i < n; i++) {
            scanf("%d %d", &a[i].first, &a[i].second);
    }

    int lf = 0;

    for(int i = 0; i < n; i++) {
            if (a[i].second == 0) {
                     ans += a[i].first;
                     lf += a[i].second - 1;
            }
    }

    sort(a, a + n);

    for(int i = n - 1; i >= 0; i--) {
            if (a[i].second == 0 && lf > 0) {
                            lf--;
                            ans += a[i].first;
            }
    }

    printf("%d", ans);

    return 0;
}


#include<iostream>
#include<algorithm>
using namespace std;
bool mycompare1(pair<int,int> p1,pair<int,int> p2)
{
	return p1.second>p2.second;
}
bool mycompare2(pair<int,int> p1,pair<int,int> p2)
{
	return p1.first>p2.first;
}
int main()
{
	int n;
	cin>>n;
	pair<int,int> a[n];
	for(int i=0;i<n;i++)
	{
		cin>>a[i].first;
		cin>>a[i].second;
	}
	sort(a,a+n,mycompare1);
//	cout<<endl;
//	for(int i=0;i<n;i++)
//	{
//		cout<<a[i].first<<" ";
//		cout<<a[i].second;
//		cout<<endl;
//	}
	int j=0;
	int c=0;
	int s=0;
	for(int i=0;i<n;i)
	{
		j=a[i].second;
		s=i;
		while(a[i].second==j && i<n)
		{
			i++;
		}
		sort(a+s,a+i,mycompare2);

	}
	int counter=a[0].second;
	int sum=a[0].first;
	int i=1;
	while(counter!=0 && i<n)
	{
		sum+=a[i].first;
		counter==a[i].second;
		counter--;
		i++;
	}
	cout<<sum;
//	cout<<endl;
//	for(int i=0;i<n;i++)
//	{
//		cout<<a[i].first<<" ";
//		cout<<a[i].second;
//		cout<<endl;
//
//	}
	return 0;
}


#include<iostream>
#include<algorithm>
using namespace std;
bool mycompare1(pair<int,int> p1,pair<int,int> p2)
{
	return p1.second>p2.second;
}
bool mycompare2(pair<int,int> p1,pair<int,int> p2)
{
	return p1.first>p2.first;
}
int main()
{
	int n;
	cin>>n;
	pair<int,int> a[n];
	for(int i=0;i<n;i++)
	{
		cin>>a[i].first;
		cin>>a[i].second;
	}
	sort(a,a+n,mycompare1);
//	cout<<endl;
//	for(int i=0;i<n;i++)
//	{
//		cout<<a[i].first<<" ";
//		cout<<a[i].second;
//		cout<<endl;
//	}
	int j=0;
	int c=0;
	int s=0;
	for(int i=0;i<n;i)
	{
		j=a[i].second;
		s=i;
		while(a[i].second==j && i<n)
		{
			i++;
		}
		sort(a+s,a+i,mycompare2);

	}
	int counter=a[0].second;
	int sum=a[0].first;
	int i=1;
	while(counter!=0 && i<n)
	{
		sum+=a[i].first;
		counter--;
		counter+=a[i].second;

		i++;
	}
	cout<<sum;
//	cout<<endl;
//	for(int i=0;i<n;i++)
//	{
//		cout<<a[i].first<<" ";
//		cout<<a[i].second;
//		cout<<endl;
//
//	}
	return 0;
}


#include<iostream>
#include<algorithm>
using namespace std;
bool mycompare1(pair<int,int> p1,pair<int,int> p2)
{
	return p1.second>p2.second;
}
bool mycompare2(pair<int,int> p1,pair<int,int> p2)
{
	return p1.first>p2.first;
}
int main()
{
	int n;
	cin>>n;
	pair<int,int> a[n];
	for(int i=0;i<n;i++)
	{
		cin>>a[i].first;
		cin>>a[i].second;
	}
	sort(a,a+n,mycompare1);
//	cout<<endl;
//	for(int i=0;i<n;i++)
//	{
//		cout<<a[i].first<<" ";
//		cout<<a[i].second;
//		cout<<endl;
//	}
	int j=0;
	int c=0;
	int s=0;
	for(int i=0;i<n;i)
	{
		j=a[i].second;
		s=i;
		while(a[i].second==j && i<n)
		{
			i++;
		}
		sort(a+s,a+i,mycompare2);

	}
	int counter=a[0].second;
	int sum=a[0].first;
	int i=1;
	while(counter!=0 && i<n)
	{
		sum+=a[i].first;
		counter==a[i].second;
		i++;
	}
	cout<<sum;
//	cout<<endl;
//	for(int i=0;i<n;i++)
//	{
//		cout<<a[i].first<<" ";
//		cout<<a[i].second;
//		cout<<endl;
//	}
	return 0;
}


//Bismillahir Rahmanir Rahim//

#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
#define pb push_back
#define gcd __gcd
#define ff first
#define ss second
#define pii pair<int, int>
#define pll pair<ll, ll>
#define vi vector<int>
#define vl vector<ll>
#define vvi vector< vector<int> >
#define fr(j, n)for(int i=j; i<n; i++)
#define scan(cr)for(auto &it:cr)cin >> it
#define _scan(cr)for(int i=1; i<cr.size(); i++)cin >> v[i]
#define all(cr)cr.begin(), cr.end()
#define sz(cr)cr.size()
#define Test() ll t, cases=0; for(cin >> t; t>0; t--)
ll lcm(ll a, ll b){ return a/gcd(a, b) * b; }

#define debug(args...) { string _s = #args; replace(_s.begin(), _s.end(), ',', ' '); stringstream _ss(_s); istream_iterator<string> _it(_ss); deb(_it, args); }
void deb(istream_iterator<string> it) {cout<<endl;}
template<typename T, typename... Args>
void deb(istream_iterator<string> it, T a, Args... args) {
    cerr << *it << " = " << a << ",   ";
    deb(++it, args...);
}
template<class A>void print(A &v){ for(auto u:v)cout << u << " "; }
template<class A>void _print(A &v){ for(auto u:v)cout << u.ff << " " << u.ss << '\n'; }
#define occ cout << "occ!!\n"
bool comp(const pii &a, const pii &b){
	return a.ss > b.ss;
}

#define mydeb(x)cout << #x << " = " << x << ","

int main()
{
	int n, ai, bi, moves=0, sum=0, i=0;
	cin >> n;	vi v;
	for(int i=0; i<n; i++)	{
		cin >> ai >> bi;
		if(bi==0)v.pb(ai);
		else if(bi==1)sum += ai;
		else {
			moves ? moves += (bi-1) : moves += bi;
			sum += ai;
		}
	}
	if(v.size()==0)cout << sum;
	else {
		sort(v.rbegin(), v.rend());
		//print(v); debug(moves); debug(i);
		if(moves==0)cout << v[0];
		else {
			while(i<sz(v) && moves){
				sum += v[i];
				//debug(sum);
				i++, moves--;
			}
			cout << sum;
		}
	}
    return 0;
}

/*****************  ALHAMDULILLAH  *****************/


//Bismillahir Rahmanir Rahim//

#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
#define pb push_back
#define gcd __gcd
#define ff first
#define ss second
#define pii pair<int, int>
#define pll pair<ll, ll>
#define vi vector<int>
#define vl vector<ll>
#define vvi vector< vector<int> >
#define fr(j, n)for(int i=j; i<n; i++)
#define scan(cr)for(auto &it:cr)cin >> it
#define _scan(cr)for(int i=1; i<cr.size(); i++)cin >> v[i]
#define all(cr)cr.begin(), cr.end()
#define sz(cr)cr.size()
#define Test() ll t, cases=0; for(cin >> t; t>0; t--)
ll lcm(ll a, ll b){ return a/gcd(a, b) * b; }

#define debug(args...) { string _s = #args; replace(_s.begin(), _s.end(), ',', ' '); stringstream _ss(_s); istream_iterator<string> _it(_ss); deb(_it, args); }
void deb(istream_iterator<string> it) {cout<<endl;}
template<typename T, typename... Args>
void deb(istream_iterator<string> it, T a, Args... args) {
    cerr << *it << " = " << a << ",   ";
    deb(++it, args...);
}
template<class A>void print(A &v){ for(auto u:v)cout << u << " "; }
template<class A>void _print(A &v){ for(auto u:v)cout << u.ff << " " << u.ss << '\n'; }
#define occ cout << "occ!!\n"
bool comp(const pii &a, const pii &b){
	return a.ss > b.ss;
}

int main()
{
	int n, ai, bi, moves=0, sum=0, i=0;
	cin >> n;	vi v;
	for(int i=0; i<n; i++)	{
		cin >> ai >> bi;
		if(moves)moves += (bi-1);
		else moves += bi;
		v.pb(ai);
	}
	sort(v.rbegin(), v.rend());
	if(moves==0)cout << v[0];
	else {
		while(moves && i<n){
			sum += v[i];
			i++, moves--;
		}
		cout << sum;
	}
    return 0;
}

/*****************  ALHAMDULILLAH  *****************/


//Bismillahir Rahmanir Rahim//

#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
#define pb push_back
#define gcd __gcd
#define ff first
#define ss second
#define pii pair<int, int>
#define pll pair<ll, ll>
#define vi vector<int>
#define vl vector<ll>
#define vvi vector< vector<int> >
#define fr(j, n)for(int i=j; i<n; i++)
#define scan(cr)for(auto &it:cr)cin >> it
#define _scan(cr)for(int i=1; i<cr.size(); i++)cin >> v[i]
#define all(cr)cr.begin(), cr.end()
#define sz(cr)cr.size()
#define Test() ll t, cases=0; for(cin >> t; t>0; t--)
ll lcm(ll a, ll b){ return a/gcd(a, b) * b; }

#define debug(args...) { string _s = #args; replace(_s.begin(), _s.end(), ',', ' '); stringstream _ss(_s); istream_iterator<string> _it(_ss); deb(_it, args); }
void deb(istream_iterator<string> it) {cout<<endl;}
template<typename T, typename... Args>
void deb(istream_iterator<string> it, T a, Args... args) {
    cerr << *it << " = " << a << ",   ";
    deb(++it, args...);
}
template<class A>void print(A &v){ for(auto u:v)cout << u << " "; }
template<class A>void _print(A &v){ for(auto u:v)cout << u.ff << " " << u.ss << '\n'; }
#define occ cout << "occ!!\n"
bool comp(const pii &a, const pii &b){
	return a.ss > b.ss;
}

#define mydeb(x)cout << #x << " = " << x << ","

int main()
{
	int n, ai, bi, i=0, moves=1, sum=0;
	cin >> n;
	vi v;
	for(int i=0; i<n; i++){
		cin >> ai >> bi;
		if(bi==0)v.pb(ai);
		else if(bi==1)sum += ai;
		else if(bi>=2){
			moves += (bi-1); sum += ai;
		}
	}
	sort(all(v), greater<int>());
	if(sz(v)==0)cout << sum;
	else if(moves==0)cout << v[0];
	else {
		i = 0;
		while(i<sz(v) && moves){
			sum += v[i];
			i++, moves--;
		}
		cout << sum;
	}
    return 0;
}

/*****************  ALHAMDULILLAH  *****************/


//Bismillahir Rahmanir Rahim//

#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
#define pb push_back
#define gcd __gcd
#define ff first
#define ss second
#define pii pair<int, int>
#define pll pair<ll, ll>
#define vi vector<int>
#define vl vector<ll>
#define vvi vector< vector<int> >
#define fr(j, n)for(int i=j; i<n; i++)
#define scan(cr)for(auto &it:cr)cin >> it
#define _scan(cr)for(int i=1; i<cr.size(); i++)cin >> v[i]
#define all(cr)cr.begin(), cr.end()
#define sz(cr)cr.size()
#define Test() ll t, cases=0; for(cin >> t; t>0; t--)
ll lcm(ll a, ll b){ return a/gcd(a, b) * b; }

#define debug(args...) { string _s = #args; replace(_s.begin(), _s.end(), ',', ' '); stringstream _ss(_s); istream_iterator<string> _it(_ss); deb(_it, args); }
void deb(istream_iterator<string> it) {cout<<endl;}
template<typename T, typename... Args>
void deb(istream_iterator<string> it, T a, Args... args) {
    cerr << *it << " = " << a << ",   ";
    deb(++it, args...);
}
template<class A>void print(A &v){ for(auto u:v)cout << u << " "; }
template<class A>void _print(A &v){ for(auto u:v)cout << u.ff << " " << u.ss << '\n'; }
#define occ cout << "occ!!\n"
bool comp(const pii &a, const pii &b){
	return a.ss > b.ss;
}

#define mydeb(x)cout << #x << " = " << x << ","

int main()
{
	int n, ai, bi, moves=0, sum=0, i=0;
	cin >> n;	vi v;
	for(int i=0; i<n; i++)	{
		cin >> ai >> bi;
		if(bi==0)v.pb(ai);
		else if(bi==1)sum += ai;
		else {
			moves ? moves += (bi-1) : moves += bi;
			sum += ai;
		}
	}
	if(v.size()==0)cout << sum;
	else {
		sort(v.rbegin(), v.rend());
		while(i<sz(v) && moves){
			sum += v[i];
			i++, moves--;
		}
		cout << sum;
	}
    return 0;
}

/*****************  ALHAMDULILLAH  *****************/


		#include<iostream>
		#include<string>
		#include<algorithm>
		#include<iterator>
		#include<vector>
		#include<algorithm>
		#include<cmath>

		using namespace std;
		pair <int,int> a[1001];

		int main() {

			int n,k=0,w=0;
			cin>>n;
			for(int i=0;i<2*n+1;i++){
				cin>>k>>w;
				a[i]=make_pair(w,k);
			}
			sort(a,a+n);
			int r=a[n-1].first,sum=a[n-1].second,i=n-2;
			for(int i=r;r>0;r--){

					r+=a[i].first;
					sum+=a[i].second;
					i--;
			}

			cout<<sum;
			return 0;
		}


		#include<iostream>
		#include<string>
		#include<algorithm>
		#include<iterator>
		#include<vector>
		#include<algorithm>
		#include<cmath>

		using namespace std;
		pair <int,int> a[1001];

		int main() {

			int n,k=0,w=0;
			cin>>n;
			for(int i=0;i<2*n+1;i++){
				cin>>k>>w;
				a[i]=make_pair(w,k);
			}
			sort(a,a+n);
			int r=a[n-1].first,sum=a[n-1].second,o=n-2;
			for(int i=r;i>0;i--){

					r+=a[o].first;
					sum+=a[o].second;
					o--;
			}

			cout<<sum;
			return 0;
		}


#include<iostream>
		#include<string>
		#include<algorithm>
		#include<iterator>
		#include<vector>
		#include<algorithm>
		#include<cmath>

		using namespace std;
		pair <int,int> a[1001];

		int main() {

			int n,k=0,w=0;
			cin>>n;
			for(int i=0;i<n;i++){
				cin>>k>>w;
				a[i]=make_pair(w,k);
			}
			sort(a,a+n);
			int i=n-1,r=a[n-1].first,sum=a[n-1].second;
			while(i-->0&&r-->0){
				r+=a[i].first;
				sum+=a[i].second;

			}

			cout<<sum;
			return 0;
		}


		#include<iostream>
		#include<string>
		#include<algorithm>
		#include<iterator>
		#include<vector>
		#include<algorithm>
		#include<cmath>

		using namespace std;
		pair <int,int> a[1001];

		int main() {

			int n,k=0,w=0;
			cin>>n;
			for(int i=0;i<2*n+1;i++){
				cin>>k>>w;
				a[i]=make_pair(w,k);
			}
			sort(a,a+n);
			int r=a[n-1].first,sum=a[n-1].second;
			for(int i=n-2;i>=0;i--){
				if(r--){
					r+=a[i].first;
					sum+=a[i].second;
				}
				else break;
			}

			cout<<sum;
			return 0;
		}


		#include<iostream>
		#include<string>
		#include<algorithm>
		#include<iterator>
		#include<vector>
		#include<algorithm>
		#include<cmath>

		using namespace std;
		pair <int,int> a[1001];

		int main() {

			//freopen("text.txt","r",stdin);
			int n,k=0,w=0;
			cin>>n;
			for(int i=0;i<2*n+1;i++){
				cin>>k>>w;
				a[i]=make_pair(w,k);
			}
			sort(a,a+n);
			int i=a[n-1].first,sum=a[n-1].second;
			while(i--){
				i+=a[i].first;
				sum+=a[i].second;
			}
			cout<<sum;
			return 0;
		}


#include<iostream>
		#include<string>
		#include<algorithm>
		#include<iterator>
		#include<vector>
		#include<algorithm>
		#include<cmath>

		using namespace std;
		pair <int,int> a[1001];

		int main() {

			int n,k=0,w=0;
			cin>>n;
			for(int i=0;i<2*n+1;i++){
				cin>>k>>w;
				a[i]=make_pair(w,k);
			}
			sort(a,a+n);
			int i=n-1,r=a[n-1].first,sum=a[n-1].second;
			while(i-->0&&r-->0){
				r+=a[i].first;
				sum+=a[i].second;

			}

			cout<<sum;
			return 0;
		}


#include<bits/stdc++.h>
using namespace std;
int main()
{
	int n;
	cin>>n;
	vector< pair<int , int> > v;
	for(int i=0;i<n;i++)
	{
		int x;
	    int y;
	    cin>>x>>y;
	    v.push_back(make_pair(y,x));
	}
	sort(v.begin(),v.end());
	reverse(v.begin(),v.end());
//	cout<<endl;
/*	for(int i=0;i<n;i++)
	{
		cout<<v[i].first<<" "<<v[i].second<<endl;
	}*/
	int steps=0;
	int ans=0;
	int i=0;
		 steps=v[i].first;
		 //cout<<"steps="<<steps<<endl;
		 if(steps==0)
		 {
		 	 ans+=v[i].second;
		 	 cout<<ans<<endl;
		 	 return 0;
		 }
		 else
		 {
		 	 ans+=v[i].second;
		 	 if(i>=n-1)
		 	 {
		 	 	//cout<<ans<<endl;
		 			return 0;
			  }
		 	while(steps)
		 	{

		 		i++;
		 		//cout<<"ff"<<" "<<i<<" "<<v[i].second<<endl;
		 		ans+=v[i].second;
		 		steps+=v[i].first;
		 		steps--;
		 		if(i>=n-1||steps==0)
		 		{
		 			cout<<ans<<endl;
		 			return 0;
				 }
				// cout<<"steps="<<steps<<endl;
			 }
		 }
	return 0;
}


#include<bits/stdc++.h>
using namespace std;
int main()
{
	int n;
	cin>>n;
	vector< pair<int , int> > v;
	for(int i=0;i<n;i++)
	{
		int x;
	    int y;
	    cin>>x>>y;
	    v.push_back(make_pair(y,x));
	}
	sort(v.begin(),v.end());
	reverse(v.begin(),v.end());
//	cout<<endl;
/*	for(int i=0;i<n;i++)
	{
		cout<<v[i].first<<" "<<v[i].second<<endl;
	}*/
	int steps=0;
	int ans=0;
	int i=0;
		 steps=v[i].first;
		 //cout<<"steps="<<steps<<endl;
		 if(steps==0)
		 {
		 	 ans+=v[i].second;
		 	 cout<<ans<<endl;
		 	 return 0;
		 }
		 else
		 {
		 	 ans+=v[i].second;
		 	while(steps)
		 	{

		 		i++;
		 		//cout<<"ff"<<" "<<i<<" "<<v[i].second<<endl;
		 		ans+=v[i].second;
		 		steps+=v[i].first;
		 		steps--;
		 		if(i>=n-1||steps==0)
		 		{
		 			cout<<ans<<endl;
		 			return 0;
				 }
				// cout<<"steps="<<steps<<endl;
			 }
		 }
	return 0;
}


#include<bits/stdc++.h>
using namespace std;
int main()
{
	int n;
	cin>>n;
	vector< pair<int , int> > v;
	for(int i=0;i<n;i++)
	{
		int x;
	    int y;
	    cin>>x>>y;
	    v.push_back(make_pair(y,x));
	}
	sort(v.begin(),v.end());
	reverse(v.begin(),v.end());
//	cout<<endl;
/*	for(int i=0;i<n;i++)
	{
		cout<<v[i].first<<" "<<v[i].second<<endl;
	}*/
	int steps=0;
	int ans=0;
	int i=0;
		 steps=v[i].first;
		 //cout<<"steps="<<steps<<endl;
		 if(steps==0)
		 {
		 	 ans+=v[i].second;
		 	 cout<<ans<<endl;
		 	 return 0;
		 }
		 else
		 {
		 	 ans+=v[i].second;
		 	 if(i>=n-1)
		 	 {
		 	 	cout<<ans<<endl;
		 			return 0;
			  }
		 	while(steps)
		 	{

		 		i++;
		 		//cout<<"ff"<<" "<<i<<" "<<v[i].second<<endl;
		 		ans+=v[i].second;
		 		steps+=v[i].first;
		 		steps--;
		 		if(i>=n-1||steps==0)
		 		{
		 			cout<<ans<<endl;
		 			return 0;
				 }
				// cout<<"steps="<<steps<<endl;
			 }
		 }
	return 0;
}


#include<bits/stdc++.h>
using namespace std;
int main()
{
	int n;
	cin>>n;
	vector< pair<int , int> > v;
	for(int i=0;i<n;i++)
	{
		int x;
	    int y;
	    cin>>x>>y;
	    v.push_back(make_pair(y,x));
	}
	sort(v.begin(),v.end());
	reverse(v.begin(),v.end());
//	cout<<endl;
/*	for(int i=0;i<n;i++)
	{
		cout<<v[i].first<<" "<<v[i].second<<endl;
	}*/
	int steps=0;
	int ans=0;
	for(int i=0;i<n;)
	{
		 steps=v[i].first;
		 //cout<<"steps="<<steps<<endl;
		 if(steps==0)
		 {
		 	 ans+=v[i].second;
		 	 cout<<ans<<endl;
		 	 return 0;
		 }
		 else
		 {
		 	 ans+=v[i].second;
		 	while(steps--)
		 	{

		 		i++;
		 		//cout<<"ff"<<" "<<i<<" "<<v[i].second<<endl;
		 		ans+=v[i].second;

		 		steps+=v[i].first;
		 		if(i==n-1||steps==0)
		 		{
		 			cout<<ans<<endl;
		 			return 0;
				 }
				// cout<<"steps="<<steps<<endl;
			 }
		 }

	}
	cout<<ans<<endl;
	return 0;
}


#include<bits/stdc++.h>
using namespace std;
int main()
{
	int n;
	cin>>n;
	vector< pair<int , int> > v;
	for(int i=0;i<n;i++)
	{
		int x;
	    int y;
	    cin>>x>>y;
	    v.push_back(make_pair(y,x));
	}
	sort(v.begin(),v.end());
	reverse(v.begin(),v.end());
//	cout<<endl;
/*	for(int i=0;i<n;i++)
	{
		cout<<v[i].first<<" "<<v[i].second<<endl;
	}*/
	int steps=0;
	int ans=0;
	for(int i=0;i<n;)
	{
		 steps+=v[i].first;
		 ans+=v[i].second;
		 if(steps==0)
		 {
		 	 cout<<ans<<endl;
		 	 return 0;
		 }
		 else
		 {
		 	while(steps--)
		 	{
		 		i++;
		 		//cout<<"ff"<<" "<<i<<" "<<v[i].second<<endl;
		 		ans+=v[i].second;
		 		if(i==n-1)
		 		{
		 			cout<<ans<<endl;
		 			return 0;
				 }
			 }
		 }
	}
	cout<<ans<<endl;
	return 0;
}


#include<bits/stdc++.h>
using namespace std;
int main()
{
	int n;
	cin>>n;
	vector< pair<int , int> > v;
	for(int i=0;i<n;i++)
	{
		int x;
	    int y;
	    cin>>x>>y;
	    v.push_back(make_pair(y,x));
	}
	sort(v.begin(),v.end());
	reverse(v.begin(),v.end());
//	cout<<endl;
/*	for(int i=0;i<n;i++)
	{
		cout<<v[i].first<<" "<<v[i].second<<endl;
	}*/
	int steps=0;
	int ans=0;
	int i=0;
		 steps=v[i].first;
		 //cout<<"steps="<<steps<<endl;
		 if(steps==0)
		 {
		 	 ans+=v[i].second;
		 	 cout<<ans<<endl;
		 	 return 0;
		 }
		 else
		 {
		 	 ans+=v[i].second;
		 	while(steps)
		 	{

		 		i++;
		 		//cout<<"ff"<<" "<<i<<" "<<v[i].second<<endl;
		 		ans+=v[i].second;
		 		steps+=v[i].first;
		 		steps--;
		 		if(i==n-1||steps==0)
		 		{
		 			cout<<ans<<endl;
		 			return 0;
				 }
				// cout<<"steps="<<steps<<endl;
			 }
		 }
	return 0;
}


#include <iostream>
#include <algorithm>
#include <string>
#include <vector>
#include <iomanip>

using namespace std;

int main()
{
    int n,m,score=0,countr=1,pivot;
    m=n;
    cin>>n;
    int arr[n][2];
    for(int i=0;i<n;i++){
        for(int j=0;j<2;j++){
            cin>>arr[i][j];
        }
    }

    for(int i=0;i<n;i++){
        for(int j=i+1;j<n;j++){
            if(arr[i][1]<arr[j][1]){
                swap(arr[i][1],arr[j][1]);
                swap(arr[i][0],arr[i][0]);
            }
    }}
    for(int i=0;i<n;i++){
        if(arr[i][1]==0){
            pivot=i;
            break;
        }
    }
    for(int i=pivot;i<n;i++){
        for(int j=i+1;j<n;j++){
            if(arr[i][0]<arr[j][0]){
                swap(arr[i][1],arr[j][1]);
                swap(arr[i][0],arr[i][0]);
            }
        }
    }

    for(int i=0;i<n;i++){
        if(arr[i][1]!=0){
            score+=arr[i][0];
            countr+=arr[i][1];
        }
        else if(m==0 || countr==0){
             break;
        }
        else{
            score+=arr[i][0];
            countr-=1;

        }
       m=m-1;
    }
    cout<<score;
}


#include <iostream>
#include <algorithm>
#include <string>
#include <vector>
#include <iomanip>

using namespace std;

int main()
{
    int n,m,score=0,countr=1,pivot;
    m=n;
    cin>>n;
    int arr[n][2];
    for(int i=0;i<n;i++){
        for(int j=0;j<2;j++){
            cin>>arr[i][j];
        }
    }

    for(int i=0;i<n;i++){
        for(int j=i+1;j<n;j++){
            if(arr[i][1]<arr[j][1]){
                swap(arr[i][1],arr[j][1]);
                swap(arr[i][0],arr[j][0]);
            }
    }}
    for(int i=0;i<n;i++){
        if(arr[i][1]==0){
            pivot=i;
            break;
        }
    }
    for(int i=pivot;i<n;i++){
        for(int j=i+1;j<n;j++){
            if(arr[i][0]<arr[j][0]){
                swap(arr[i][0],arr[j][0]);
                swap(arr[i][1],arr[j][1]);
            }
        }
    }

    for(int i=0;i<n;i++){
        if(countr!=0){
            score+=arr[i][0];
            countr+=arr[i][1]-1;
        }
        else{
             break;
        }
       m=m-1;
    }
    cout<<score;
}


#include <iostream>
#include <algorithm>
#include <string>
#include <vector>
#include <iomanip>

using namespace std;

int main()
{
    int n,m,score=0,countr=1,pivot;
    m=n;
    cin>>n;
    int arr[n][2];
    for(int i=0;i<n;i++){
        for(int j=0;j<2;j++){
            cin>>arr[i][j];
        }
    }

    for(int i=0;i<n;i++){
        for(int j=i+1;j<n;j++){
            if(arr[i][1]<arr[j][1]){
                swap(arr[i][1],arr[j][1]);
                swap(arr[i][0],arr[i][0]);
            }
    }}
    for(int i=0;i<n;i++){
        if(arr[i][1]==0){
            pivot=i;
            break;
        }
    }
    for(int i=pivot;i<n;i++){
        for(int j=i+1;j<n;j++){
            if(arr[i][0]<arr[j][0]){
                swap(arr[i][0],arr[j][0]);
            }
        }
    }

    for(int i=0;i<n;i++){
        if(m!=0 && countr!=0){
            score+=arr[i][0];
            countr+=arr[i][1]-1;
        }
        else{
             break;
        }
       m=m-1;
    }
    cout<<score;
}


#include <bits/stdc++.h>

#define x first

#define y second

#define eps 1e-8

#define pb push_back

#define mod 1000000007

#define inf 0x3f3f3f3f

#define INF 0x3f3f3f3f3f3f3f3fLL

#define bit(x, y) (((x)>>(y))&1)

#define bctz(x) (__builtin_ctz(x))

#define bclz(x) (__builtin_clz(x))

#define bclzl(x) (__builtin_clzll(x))

#define bctzl(x) (__builtin_ctzll(x))

#define bpt(x) (__builtin_popcount(x))

#define bptl(x) (__builtin_popcountll(x))

#define PQ priority_queue<pii, vector<pii>, greater<pii> >

using namespace std;

typedef double DO;

typedef long long INT;

typedef pair<int, int> pii;

typedef pair<pii, int> pi3;

typedef vector<int> VI;

template<typename T, typename U> inline void smin(T &a, const U &b) {if(a>b) a=b;}

template<typename T, typename U> inline void smax(T &a, const U &b) {if(a<b) a=b;}

template<typename T> inline void gn(T &x) {char c, sg=0; while (c=getchar(), (c>'9' || c<'0') && c!='-');for((c=='-'?sg=1, c=getchar():0), x=0; c>='0' && c<='9'; c=getchar()) x=(x<<1)+(x<<3)+c-'0';if (sg) x=-x;}

template<class T, class T1>inline void gn(T &x, T1 &y) {gn(x); gn(y);}

template<class T, class T1, class T2>inline void gn(T &x, T1 &y, T2 &z) {gn(x); gn(y); gn(z);}

template<typename T> inline void print(T x) {if (x<0) {putchar('-');return print(-x);}if (x<10) {putchar('0'+x);return;} print(x/10);putchar(x%10+'0');}

template<typename T> inline void println(T x) {print(x), putchar('\n');}

template<typename T> inline void printsp(T x) {print(x), putchar(' ');}

template<class T, class T1> inline void print(T x, T1 y) {printsp(x), println(y);}

template<class T, class T1, class T2> inline void print(T x, T1 y, T2 z) {printsp(x), printsp(y), println(z);}

int power(int a, int b, int m, int ans=1) {

	for (; b; b>>=1, a=(INT)a*a%m) if (b&1) ans=(INT)ans*a%m;

	return ans;

}

#define NN 1010

int a[NN],b[NN];

pii p[NN];

int main() {

#ifndef ONLINE_JUDGE

	freopen("in.in", "r", stdin);

	freopen("out.out", "w", stdout);

#endif

	int n;

	scanf("%d",&n);

	for(int i=1;i<=n;i++){

		scanf("%d%d",&a[i],&b[i]);

		p[i].x=b[i],p[i].y=a[i];

	}

	sort(p+1,p+n+1);

	int ans=0;

	int st=1;

	for(int i=n;i>=1;i--){

		if(st){

			ans+=p[i].y;

			st+=p[i].x-1;

		}

		else break;

	}

	printf("%d\n",ans);

	return 0;

}


#include<bits/stdc++.h>

#define x first
#define y second
#define pb push_back
#define inf 0x3f3f3f3f
#define mod 1000000007
#define sq(x) ((x)*(x))
#define bit(x, y) (((x)>>(y))&1)
#define bctz(x) (__builtin_ctz(x))
#define bclz(x) (__builtin_clz(x))
#define bclzl(x) (__builtin_clzl(x))
#define bctzl(x) (__builtin_ctzl(x))
#define bpt(x) (__builtin_popcount(x))
#define bptl(x) (__builtin_popcountll(x))
#define PQ priority_queue<pii, vector<pii>, greater<pii> >
#define eps 1e-8
#define squ(a, b) (a)*(a)+(b)*(b)
#define pi 3.1415926535897932384626433832795

using namespace std;

typedef double DO;
typedef long long INT;
typedef pair<int, int> pii;
typedef pair<pii, int> pi3;
typedef vector<int> VI;

template<typename T, typename U> inline void smin(T &a, const U &b) {if(a>b) a=b;}
template<typename T, typename U> inline void smax(T &a, const U &b) {if(a<b) a=b;}

template <class T> inline void gn(T &x) {char c, sg=0; while(c=getchar(), (c>'9' || c<'0') && c!='-'); for((c=='-' ? sg=1, c=getchar() : 0), x=0; c>='0' && c<='9'; c=getchar()) x=(x<<1)+(x<<3)+c-'0'; if(sg) x=-x;}
template <class T1, class T2> inline void gn(T1 &x1, T2 &x2) {gn(x1), gn(x2);}
template <class T1, class T2, class T3> inline void gn(T1 &x1, T2 &x2, T3 &x3) {gn(x1, x2), gn(x3);}
template <class T1, class T2, class T3, class T4> inline void gn(T1 &x1, T2 &x2, T3 &x3, T4 &x4) {gn(x1, x2, x3), gn(x4);}
template <class T1, class T2, class T3, class T4, class T5> inline void gn(T1 &x1, T2 &x2, T3 &x3, T4 &x4, T5 &x5) {gn(x1, x2, x3, x4), gn(x5);}

template <class T> inline void print(T x) {if(x<0) {putchar('-'); return print(-x);} if(x<10) {putchar('0'+x); return ;} print(x/10); putchar(x%10+'0');}
template <class T> inline void println(T x) {print(x); putchar('\n');}
template <class T> inline void printsp(T x) {print(x); putchar(' ');}
template <class T1, class T2> inline void print(T1 x1, T2 x2) {printsp(x1), println(x2);}
template <class T1, class T2, class T3> inline void print(T1 x1, T2 x2, T3 x3) {printsp(x1), printsp(x2), println(x3);}
template <class T1, class T2, class T3, class T4> inline void print(T1 x1, T2 x2, T3 x3, T4 x4) {printsp(x1), printsp(x2), printsp(x3), println(x4);}
template <class T1, class T2, class T3, class T4, class T5> inline void print(T1 x1, T2 x2, T3 x3, T4 x4, T5 x5) {printsp(x1), printsp(x2), printsp(x3), printsp(x4), println(x5);}

int power(int a, int b, int m, int ans=1) {
	for (; b; b>>=1, a=1LL*a*a%m) if (b&1) ans=1LL*ans*a%m;
	return ans;
}

#define NN 1111

pii p[NN];

bool cmp(pii a, pii b){
	if(a.y==b.y)	return a.x>b.x;
	return a.y>b.y;
}

int main(){
#ifndef ONLINE_JUDGE
	freopen("in.in", "r", stdin);
	freopen("out.out", "w", stdout);
#endif

	int n;
	gn(n);

	for(int i=0; i<n; i++){
		gn(p[i].x, p[i].y);
	}

	sort(p, p+n, cmp);

	INT ans=0, cnt=1;
	for(int i=0; i<n and cnt; i++){

		ans+=p[i].x;
		cnt+=p[i].y;
		cnt--;
	}

	println(ans);

	return 0;
}