#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <cstring>
#include <string>
#include <algorithm>
#include <ctime>
#include <cstdlib>
#include <queue>
#include <iomanip>
#include <climits>
#include <list>
#include <stack>
#include <map>
using namespace std;
#define mod 1000000007;
struct card{
	int a;
	int b;
};
bool func(card & c1,card & c2){
	if(c1.b == c2.b)
		return c1.a > c2.a;
	return c1.b > c2.b;
}
int main(){
	int n;
	cin >> n;
	card c[n];
	for(int i = 0; i < n; i++){
		cin >> c[i].a >> c[i].b;
	}
	sort(c,c+n,func);
	long long p = c[0].a;
	long long n2 = c[0].b;

	for(int i = 1; i < n && n2 > 0; i++){
		p += c[i].a;
		n2--;
		n2 += c[i].b;
	}
	cout<<p;
	return 0;
}


#include<bits/stdc++.h>
using namespace std;
struct tash
{
	int point;
	int count;
};

int main()
{
	int n,total=0,chance=1;
	cin>>n;
  if(n==1)
  {
    int l,m;
    cin>>l>>m;
    cout<<l;
    return 0;
  }
	tash cards[n],temp;
	for(int i=0;i<n;i++)
	{
		cin>>cards[i].point>>cards[i].count;
	}
  cout<<endl;
 /* for(int i=0;i<n ;i++)
    {
      cout<<cards[i].point<<"  "<<cards[i].count<<endl;
    }*/

    cout<<endl;

	for(int j=0;j<n;j++)
		for(int i=0;i<n-1;i++)
		{
			if(cards[i].count>cards[i+1].count || cards[i].count==cards[i+1].count && cards[i].point>cards[i+1].point)
			{
					temp=cards[i];
					cards[i]=cards[i+1];
					cards[i+1]=temp;
			}
		}

    /*for(int i=0;i<n ;i++)
    {
      cout<<cards[i].point<<"  "<<cards[i].count<<endl;
    }*/
		int k=n-1;
	while(chance>0 && k>0)
	{
		total+=cards[k].point;
		chance=chance-1;
		chance=chance+cards[k].count;
		k--;
	}

	cout<<total;
	return 0;
}


#include<bits/stdc++.h>
using namespace std;
struct tash
{
	int point;
	int count;
};

int main()
{
	int n,total=0,chance=1;
	cin>>n;
  if(n==1)
  {
    int l,m;
    cin>>l>>m;
    cout<<l;
    return 0;
  }
	tash cards[n],temp;
	for(int i=0;i<n;i++)
	{
		cin>>cards[i].point>>cards[i].count;
	}
  cout<<endl;
 /* for(int i=0;i<n ;i++)
    {
      cout<<cards[i].point<<"  "<<cards[i].count<<endl;
    }*/

    cout<<endl;

	for(int j=0;j<n;j++)
		for(int i=0;i<n-1;i++)
		{
			if(cards[i].count>cards[i+1].count || cards[i].count==cards[i+1].count && cards[i].point>cards[i+1].point)
			{
					temp=cards[i];
					cards[i]=cards[i+1];
					cards[i+1]=temp;
			}
		}

    /*for(int i=0;i<n ;i++)
    {
      cout<<cards[i].point<<"  "<<cards[i].count<<endl;
    }*/
		int k=n-1;
	while(chance>0)
	{
		total+=cards[k].point;
		chance=chance-1;
		chance=chance+cards[k].count;
		k--;
	}

	cout<<total;
	return 0;
}


#include<bits/stdc++.h>
using namespace std;
struct tash
{
	int point;
	int count;
};

int main()
{
	int n,total=0,chance=1;
	cin>>n;
 /* if(n==1)
  {
    int l,m;
    cin>>l>>m;
    cout<<l;
    return 0;
  }*/
	tash cards[n],temp;
	for(int i=0;i<n;i++)
	{
		cin>>cards[i].point>>cards[i].count;
	}
  cout<<endl;
 /* for(int i=0;i<n ;i++)
    {
      cout<<cards[i].point<<"  "<<cards[i].count<<endl;
    }*/

    cout<<endl;

	for(int j=0;j<n;j++)
		for(int i=0;i<n-1;i++)
		{
			if(cards[i].count>cards[i+1].count || cards[i].count==cards[i+1].count && cards[i].point>cards[i+1].point)
			{
					temp=cards[i];
					cards[i]=cards[i+1];
					cards[i+1]=temp;
			}
		}

    /*for(int i=0;i<n ;i++)
    {
      cout<<cards[i].point<<"  "<<cards[i].count<<endl;
    }*/
		int k=n-1;
	while(chance>0 && k>=0)
	{
		total+=cards[k].point;
		chance=chance-1;
		chance=chance+cards[k].count;
		k--;
	}

	cout<<total;
	return 0;
}


#include<bits/stdc++.h>
using namespace std;
struct tash
{
	int point;
	int count;
};

int main()
{
	int n,total=0,chance=1;
	cin>>n;
	tash cards[n],temp;
	for(int i=0;i<n;i++)
	{
		cin>>cards[i].point>>cards[i].count;
	}
  cout<<endl;
 /* for(int i=0;i<n ;i++)
    {
      cout<<cards[i].point<<"  "<<cards[i].count<<endl;
    }*/

    cout<<endl;

	for(int j=0;j<n;j++)
		for(int i=0;i<n-1;i++)
		{
			if(cards[i].count>cards[i+1].count || cards[i].count==cards[i+1].count && cards[i].point>cards[i+1].point)
			{
					temp=cards[i];
					cards[i]=cards[i+1];
					cards[i+1]=temp;
			}
		}

    /*for(int i=0;i<n ;i++)
    {
      cout<<cards[i].point<<"  "<<cards[i].count<<endl;
    }*/
		int k=n-1;
	while(chance>0)
	{
		total+=cards[k].point;
		chance=chance-1;
		chance=chance+cards[k].count;
		k--;
	}

	cout<<total;
	return 0;
}


#include<bits/stdc++.h>
using namespace std;
struct tash
{
	int point;
	int count;
};

int main()
{
	int n,total=0,chance=1;
	cin>>n;
  if(n==1)
  {
    int l,m;
    cin>>l>>m;
    cout<<l;
    return 0;
  }
	tash cards[n],temp;
	for(int i=0;i<n;i++)
	{
		cin>>cards[i].point>>cards[i].count;
	}
  cout<<endl;
 /* for(int i=0;i<n ;i++)
    {
      cout<<cards[i].point<<"  "<<cards[i].count<<endl;
    }*/

    cout<<endl;

	for(int j=0;j<n;j++)
		for(int i=0;i<n-1;i++)
		{
			if(cards[i].count>cards[i+1].count || cards[i].count==cards[i+1].count && cards[i].point>cards[i+1].point)
			{
					temp=cards[i];
					cards[i]=cards[i+1];
					cards[i+1]=temp;
			}
		}

    /*for(int i=0;i<n ;i++)
    {
      cout<<cards[i].point<<"  "<<cards[i].count<<endl;
    }*/
		int k=n-1;
	while(chance>0 && k>=0)
	{
		total+=cards[k].point;
		chance=chance-1;
		chance=chance+cards[k].count;
		k--;
	}

	cout<<total;
	return 0;
}


#include <iostream>
#include <algorithm>
#include <cmath>
#include <string>
#include <vector>
#include <map>
#include <iomanip>
#include <cstring>
using namespace std;
typedef long long ll;
#define pb push_back
#define all v.begin(),v.end()
const int N=1e5+100;
const int mod =1e9+7;
int n,a,b,k,c;
vector <pair<int,int> > v;
vector <int>f;
bool vis[10010];
int main(){
    ios_base::sync_with_stdio(0); cin.tie(NULL);
    cin >> n;
    for(int i=0;i<n;i++){
        int x,y;
        cin >>x>>y;
        if (x==0&&y==0)continue;
        if (x==0)f.push_back(y);
        else v.push_back(make_pair(y,x));
    }
    int r=1;
    sort(f.begin(),f.end());
    reverse(f.begin(),f.end());
    for (int i=0;i<(int)f.size();i++){
        if (f[i]==0)continue;
        r--;
        r+=f[i];
    }
    sort(all);
    reverse (all);
    int ans=0;
    for (int i=0;i<(int)v.size();i++){
        if (r==0)break;
        ans+=v[i].second;
        r--;
        r+=v[i].first;
    }
    cout <<ans<<endl;

    return 0;
}


#include <iostream>
#include <algorithm>
#include <cmath>
#include <string>
#include <vector>
#include <map>
#include <iomanip>
#include <cstring>
using namespace std;
typedef long long ll;
#define pb push_back
#define all v.begin(),v.end()
const int N=1e5+100;
const int mod =1e9+7;
int n,a,b,k,c;
vector <pair<int,int> > v;
vector <int>f;
bool vis[10010];
int main(){
    ios_base::sync_with_stdio(0); cin.tie(NULL);
    cin >> n;
    for(int i=0;i<n;i++){
        int x,y;
        cin >>x>>y;
        if (x==0)f.push_back(y);
        else v.push_back(make_pair(x,y));
    }
    int r=1;
    sort(f.begin(),f.end());
    reverse(f.begin(),f.end());
    for (int i=0;i<(int)f.size();i++){
        if (f[i]==0)continue;
        r--;
        r+=f[i];
    }
    sort(all);
    reverse (all);
    int ans=0;
    for (int i=0;i<(int)v.size();i++){
        if (r==0)break;
        ans+=v[i].first;
        r--;
        r+=v[i].second;
    }
    cout <<ans<<endl;

    return 0;
}


#include <iostream>
#include <algorithm>
#include <cmath>
#include <string>
#include <vector>
#include <map>
#include <iomanip>
#include <cstring>
using namespace std;
typedef long long ll;
#define pb push_back
#define all v.begin(),v.end()
const int N=1e5+100;
const int mod =1e9+7;
int n,a,b,k,c;
vector <pair<int,int> > v;
vector <int>f;
bool vis[10010];
int main(){
    ios_base::sync_with_stdio(0); cin.tie(NULL);
    cin >> n;
    for(int i=0;i<n;i++){
        int x,y;
        cin >>x>>y;
        if (x==0)f.push_back(y);
        else v.push_back(make_pair(x,y));
    }
    int r=1;
    sort(f.begin(),f.end());
    reverse(f.begin(),f.end());
    for (int i=0;i<(int)f.size();i++){
        r--;
        r+=f[i];
    }
    sort(all);
    reverse (all);
    int ans=0;
    for (int i=0;i<(int)v.size();i++){
        if (r==0)break;
        ans+=v[i].first;
        r--;
        r+=v[i].second;
    }
    cout <<ans<<endl;

    return 0;
}


#include <iostream>
#include <algorithm>
#include <cmath>
#include <math.h>
#include <string>
#include <vector>
#include <map>
#include <set>
#include <stack>
#include <iomanip>
#include <cstring>
#include <queue>
#include <bitset>
using namespace std;
typedef long long ll;
#define pb push_back
#define all v.begin(),v.end()
const int N=1e6+100;
const double PI=3.14159;
vector <pair<int,int> >v;
ll n,m,k,t,sum,r,l,d,b,c,a[70],p[6];
ll ans[6];
map<int,int>mp;
bool f;
string s;
stack<char>st;
int main(){
    ios_base::sync_with_stdio(0); cin.tie(NULL);
    cin >>n;
    for (int i=0;i<n;i++){
        int x,y;
        cin >>x>>y;
        v.push_back(make_pair(y,x));
    }
    sort(v.begin(),v.end());
    for (int i=0;i<n;i++){
        for (int j=0;j<n;j++){
            if (v[i].first==v[j].first){
                if (v[i].second<v[j].second){
                    swap(v[i].second,v[j].second);

                }
            }
        }
    }
    reverse(v.begin(),v.end());
    c=1;
    for(int i=0;i<n;i++){
        if (!c)break;
        c--;
        c+=v[i].first;
        sum+=v[i].second;
    }
    cout <<sum<<endl;
    return 0;
}


#include <bits/stdc++.h>

using namespace std;

priority_queue <pair <int, int> > q;
int g = 0;

void solve (int n) {
    if (!n) {g += q.top().second; q.pop(); return;}
    while (n>0 && !q.empty()){
        n--;
        //cout << q.top().first << " " << q.top().second << endl;
        g += q.top().second;
        q.pop();
       if (!q.empty()&& n>0) solve(q.top().first);
       // q.pop();
    }
    return;
}

int main () {
    int k;
    cin >> k;
    while (k--) {
        int a, b;
        cin >> a >> b;
        q.push(make_pair(b, a)) ;
    }
    solve (q.top().first);
    cout <<  g;
}


#include <bits/stdc++.h>

using namespace std;

priority_queue <pair <int, int> > q;
int g = 0;

void solve (int n) {
    if (!n) {g += q.top().second; q.pop(); return;}
    while (n>0 && !q.empty()){
        n--;
        //cout << q.top().first << " " << q.top().second << endl;
        g += q.top().second;
        q.pop();
       if (!q.empty()) solve(q.top().first);
       // q.pop();
    }
    return;
}

int main () {
    int k;
    cin >> k;
    while (k--) {
        int a, b;
        cin >> a >> b;
        q.push(make_pair(b, a)) ;
    }
    solve (q.top().first);
    cout <<  g;
}


#include <bits/stdc++.h>

using namespace std;

priority_queue <pair <int, int> > q;
int g = 0;

void solve (int n) {
    if (!n) {g += q.top().second;  q.pop(); return;}
    while (n>0 && !q.empty()){

        //cout << q.top().first << " " << q.top().second << endl;
        g += q.top().second;
        q.pop();
       if (!q.empty()&& n>0) solve(q.top().first);
       n--;
       // q.pop();
    }
    return;
}

int main () {
    int k;
    cin >> k;
    while (k--) {
        int a, b;
        cin >> a >> b;
        q.push(make_pair(b, a)) ;
    }
    solve (q.top().first);
    cout <<  g;
}


#include<bits/stdc++.h>

using namespace std;

int n;
priority_queue <pair <int, int> > q;
priority_queue <pair <int, int> > q1;
stack <int> s;

int main () {
    int k;
    cin >> k;
    while (k--) {
        int a, b;
        cin >> a >> b;
        q.push(make_pair(b, a)) ;
        q1.push(make_pair(b, a)) ;
    }
    /*while (q1.size()) {
        cout << q1.top().first << ' ' << q1.top().second << endl;
        q1.pop();
    }*/
    int g = 0;
   // while (q.size()) {
        g += q.top().second;
        s.push(q.top().first);
        q.pop();
        while ( q.size() && s.size()) {
             if (s.top()<=0) {s.pop(); continue;}
            //cout << s.top() << endl;;
            g += q.top().second;
            s.top()--;

            s.push(q.top().first);
            q.pop();
        }
    //}
    cout <<  g;
}


#include <iostream>
#include <vector>
#include <algorithm>
#include <iomanip>
#include <string>
#include <map>
#define ll long long
#define f(i,m,n) for(ll i=m;i<=n;i++)
using namespace std;

bool sortinrev1(const pair<int,int> &a,
               const pair<int,int> &b)
{
       return (a.first > b.first);
}
bool sortinrev2(const pair<int,int> &a,
               const pair<int,int> &b)
{
       return (a.second > b.second);
}

int main(){

int n;
cin>>n;
vector<int> a(n),b(n);
vector<pair<int,int>> m1(n),m2(n);
ll p=0,z=0;
for(int i=0;i<n;i++){
	cin>>a[i]>>b[i];
	m1[i].first=a[i];
	m2[i].first=a[i];
	m1[i].second=b[i];
	m2[i].second=b[i];
}
	sort(m1.begin(),m1.end(),sortinrev1);
	sort(m2.begin(),m2.end(),sortinrev2);
	int i=0;int x=m2[0].second;p+=m2[0].first;
	bool fuse=true;
	while(x>0 && i<n-1){
		i++;
		p+=m2[i].first;
		if(m2[i].second>0 && fuse){x+=m2[i].second;}
		if(m2[i].second<0){fuse=false;}
		x--;
	}
	i=0; x=m1[0].second;fuse=true;z+=m1[0].first;
	while(i<n-1 && x>0){
		i++;
		z+=m1[i].first;
		if(m1[i].second>0 && fuse){x+=m1[i].second;}
		if(m1[i].first){fuse=false;}
		x--;
	}
	cout<<max(p,z)<<endl;
	//f(i,0,n-1)cout<<m2[i].first<<" "<<m2[i].second<<endl;

return 0;
}


#include <iostream>
#include <vector>
#include <algorithm>
#include <iomanip>
#include <string>
#include <map>
#define ll long long
#define f(i,m,n) for(ll i=m;i<=n;i++)
using namespace std;

bool sortinrev1(const pair<int,int> &a,
               const pair<int,int> &b)
{
       return (a.first > b.first);
}
bool sortinrev2(const pair<int,int> &a,
               const pair<int,int> &b)
{
       return (a.second > b.second);
}

int main(){

int n;
cin>>n;
vector<int> a(n),b(n);
vector<pair<int,int>> m1(n),m2(n);
ll p=0,z=0;
for(int i=0;i<n;i++){
	cin>>a[i]>>b[i];
	m1[i].first=a[i];
	m2[i].first=a[i];
	m1[i].second=b[i];
	m2[i].second=b[i];
}
	sort(m1.begin(),m1.end(),sortinrev1);
	sort(m2.begin(),m2.end(),sortinrev2);
	int i=0;int x=m2[0].second;p+=m2[0].first;
	bool fuse=true;
	while(x>0 && i<n-1){
		i++;
		p+=m2[i].first;
		if(m2[i].second>0 && fuse){x+=m2[i].second;}
		if(m2[i].second<0){fuse=false;}
		x--;
	}
	i=0; x=m1[0].second;fuse=true;z+=m1[0].first;
	while(i<n-1 && x>0){
		i++;
		z+=m1[i].first;
		if(m1[i].second>0 && fuse){x+=m1[i].second;}
		if(m1[i].first){fuse=false;}
		x--;
	}
	cout<<max(p,z)<<p<<z<<endl;
	//f(i,0,n-1)cout<<m2[i].first<<" "<<m2[i].second<<endl;

return 0;
}


#include <iostream>
#include <vector>
#include <algorithm>
#include <iomanip>
#include <string>
#include <map>
#define ll long long
#define f(i,m,n) for(ll i=m;i<=n;i++)
using namespace std;

int main(){

int n;
cin>>n;
map<int,int> m1,m2;
vector<int> a(n),b(n);
ll p=0,z=0;
for(int i=0;i<n;i++){
	cin>>a[i]>>b[i];
	m1[a[i]]=b[i];
	m2[b[i]]=a[i];
}
	sort(a.begin(),a.end());
	sort(b.begin(),b.end());
	int i=0;int x=b[0];p+=m2[b[0]];
	bool fuse=true;
	while(x>0 && i<n-1){
		i++;
		p+=m2[b[i]];
		if(b[i]>0 && fuse){x+=b[i];fuse=false;}

		x--;
	}
	i=0; x=m1[a[0]];fuse=true;z+=a[0];
	while(i<n-1 && x>0){
		i++;
		z+=a[i];
		if(m1[a[i]]>0 && fuse){x+=m1[a[i]];fuse=false;}

		x--;
	}
	cout<<max(p,z)<<endl;

return 0;
}


#include <iostream>
#include <vector>
#include <algorithm>
#include <iomanip>
#include <string>
#include <map>
#define ll long long
#define f(i,m,n) for(ll i=m;i<=n;i++)
using namespace std;

bool sortinrev1(const pair<int,int> &a,
               const pair<int,int> &b)
{
       return (a.first > b.first);
}
bool sortinrev2(const pair<int,int> &a,
               const pair<int,int> &b)
{
       return (a.second > b.second);
}

int main(){

int n;
cin>>n;
vector<int> a(n),b(n);
vector<pair<int,int>> m1(n),m2(n);
ll p=0,z=0;
for(int i=0;i<n;i++){
	cin>>a[i]>>b[i];
	m1[i].first=a[i];
	m2[i].first=a[i];
	m1[i].second=b[i];
	m2[i].second=b[i];
}
	sort(m1.begin(),m1.end(),sortinrev1);
	sort(m2.begin(),m2.end(),sortinrev2);
	int i=0;int x=m2[i].second;p+=m2[0].first;
	bool fuse=true;
	while(x>0 && i<n-1){
		i++;
		p+=m2[i].first;
		if(m2[i].second>0 && fuse){x+=m2[i].second;fuse=false;}
		x--;
	}
	i=0; x=m1[0].second;fuse=true;z+=m1[0].first;
	while(i<n-1 && x>0){
		i++;
		z+=m1[i].first;
		if(m1[i].second>0 && fuse){x+=m1[i].second;fuse=false;}
		x--;
	}
	cout<<max(p,z)<<endl;
	//f(i,0,n-1)cout<<m1[i].first<<" "<<m1[i].second<<endl;

return 0;
}


#include <cstdio>
#include <algorithm>

using namespace std;

struct card
{
    int a;
    int b;
};

bool cmp(const card& left, const card& right)
{
    return (left.b > right.b)
        || (left.b == right.b && left.a > right.a);
}

int main()
{
    int n;
    scanf("%d", &n);

    card c[1000];
    for (int i = 0; i < n; ++i)
    {
        scanf("%d%d", &c[i].a, &c[i].b);
    }

    sort(c, c + n, cmp);
    int points(c[0].a), cards(c[0].b);
    for (int i = 1; i < n && i <= cards; ++i)
    {
        points += c[i].a;
        cards += c[i].b;
    }

    printf("%d\n", points);
    return 0;
}


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

int main()
{
	int n;
	cin >> n;
	pair<int, int> p[1005];
	for (int i = 0; i < n; i++) {
		cin >> p[i].first >> p[i].second;
	}
	for (int i = 0; i < n; i++) {
		for (int j = i + 1; j < n; j++) {
			if (p[i].second < p[j].second) {
				swap(p[i], p[j]);
			}
			else if (p[i].second == p[j].second) {
				if (p[i].first < p[j].first) {
					swap(p[i], p[j]);
				}
			}
		}
	}
	int res = 0, cards = 1;
	for (int i = 0; i < n; i++) {
		res += p[i].first;
		cards += p[i].second - 1;
		if (cards == 0)
			break;
	}
	cout << res << endl;
	return 0;
}


#include <iostream>
#include <string>
#include <iomanip>
#include <algorithm>
#include <map>
#include <cmath>
#include <set>
#include <vector>
#include <string.h>
//#include <sstream>
using namespace std;

int main()
{
	int n;
	pair<int, int> p[1003];
	cin >> n;
	for (int i = 0; i < n; i++) {
		cin >> p[i].first >> p[i].second;
	}
	for (int i = 0; i < n; i++) {
		for (int j = i + 1; j < n; j++) {
			if (p[i].second < p[j].second) {
				swap(p[i], p[j]);
			}
			else if (p[i].second == p[j].second) {
				if(p[i].first < p[j].first)
					swap(p[i], p[j]);
			}
		}
	}

	int cntr = 0, cards = 1, maxi = 0, x = 0;
	for (int i = 0; i < n; i++) {
		if (cards == 0) {
			maxi = max(maxi, cntr);
			cntr -= p[x].first;
			x++;
		}
		cntr += p[i].first;
		cards += p[i].second - 1;
	}
	maxi = max(maxi, cntr);
	cout << maxi << endl;
	return 0;
}


#include <iostream>
#include <string>
#include <iomanip>
#include <algorithm>
#include <map>
#include <cmath>
#include <set>
#include <vector>
#include <string.h>
//#include <sstream>
using namespace std;

int main()
{
	int n;
	pair<int, int> p[1003];
	cin >> n;
	for (int i = 0; i < n; i++) {
		cin >> p[i].first >> p[i].second;
	}
	for (int i = 0; i < n; i++) {
		for (int j = i + 1; j < n; j++) {
			if (p[i].second < p[j].second) {
				swap(p[i], p[j]);
			}
			else if (p[i].second == p[j].second) {
				if(p[i].first < p[j].first)
					swap(p[i], p[j]);
			}
		}
	}

	int cntr = 0, cards = 1, maxi = 0, x = 0;
	for (int i = 0; i < n; i++) {
		if (cards == 0) {
			maxi = max(maxi, cntr);
			cntr -= p[x].first;
			x++;
			cards = 1;
		}
		cntr += p[i].first;
		cards += p[i].second - 1;
	}
	maxi = max(maxi, cntr);
	cout << maxi << endl;
	return 0;
}


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

int main()
{
	int n;
	cin >> n;
	pair<int, int> p[1005];
	for (int i = 0; i < n; i++) {
		cin >> p[i].first >> p[i].second;
	}
	for (int i = 0; i < n; i++) {
		for (int j = i + 1; j < n; j++) {
			if (p[i].second < p[i].first) {
				swap(p[i], p[j]);
			}
			else if (p[i].second == p[i].first) {
				if (p[i].first < p[j].first) {
					swap(p[i], p[j]);
				}
			}
		}
	}
	int res = 0, cards = 1;
	for (int i = 0; i < n; i++) {
		res += p[i].first;
		cards += p[i].second - 1;
		if (cards == 0)
			break;
	}
	cout << res << endl;
	return 0;
}


#include <bits/stdc++.h>
#include <ext/pb_ds/assoc_container.hpp>
#include <ext/pb_ds/tree_policy.hpp>
using namespace std;
using namespace __gnu_pbds;
template <typename T>
using ordered_set = tree<T,null_type, less<T>, rb_tree_tag, tree_order_statistics_node_update>;
#define SPEED ios::sync_with_stdio(false); cin.tie(0); cout.tie(0)
#define fileio freopen("in.in", "r", stdin),freopen("out.out", "w", stdout);
#define ll long long
#define ld long double
#define fi first
#define se second
#define mp make_pair
#define pb push_back
#define eb emplace_back
#define pll pair<long long ,long long >
#define ppll pair < pll , pll >
#define sd(x) scanf("%d",&x)
#define sld(x) scanf("%lld",&x)
#define INF 1e18
#define eps 0.00001
#define le length
#define debug(n1) cout << n1 << endl
#define rep(i , j , n) for(ll i = j ; i <= n ; i++)
#define per(i , j , n) for(ll i = j ; i >= n ; i--)
const ll N = 1e5 + 5;
const ll MAX = 3e5 + 5;
const ll M = 1e6 + 5;
const ll mod = 2e18 + 7;
ll MODULAR_POWER(ll a , ll b , ll MOD) {
    if(b == 0) return 1LL;
    ll d = MODULAR_POWER(a , b / 2 , MOD);
    d *= d;
    d %= MOD;
    if(b % 2) d *= a;
    d %= MOD;
    return d;
}
ll MODULAR_INVERSE(ll a , ll MOD) {
    return MODULAR_POWER(a , MOD - 2 , MOD);
}
ll BINARY_SEARCH(ll dp[] , ll n , ll key) {
    ll s = 1;
    ll e = n;
    while(s <= e) {
        ll mid = (s + e) / 2;
        if(dp[mid] == key) return mid;
        else if (dp[mid] > key) e = mid - 1;
        else s = mid + 1;
    }
    return -1;
}
string CONVERT_TO_BINARY(ll s) {
    string res = "";
    while(s != 0) {
        res += (char)('0' + s % 2);
        s /= 2;
    }
    reverse(res.begin() , res.end());
    return res;
}
bool PALINDROME(string s) {
    ll i = 0;
    ll j = s.le() - 1;
    while(i <= j) {
        if(s[i] != s[j]) return false;
        j-- , i++;
    }
}
ll n;
pll a[N];
pll b[N];
int main() {
    SPEED;
    cout.precision(8);
    cout << fixed;
    cin >> n;
    int u = 0;
    int v = 0;
    rep(i , 1 , n) {
        int x , y;
        cin >> x >> y;
        if(y > 0) {
            b[++u].fi = x;
            b[u].se = y;
        }
        else {
            a[++v].fi = x;
            a[v].se = y;
        }
    }
    sort(a + 1 , a + u + 1);
    ll sum = 0;
    ll sum1 = 0;
    rep(i , 1 , u) sum += b[i].fi;
    rep(i , 1 , u) sum1 += b[i].se;
    if(sum1 == 0) {
        cout << a[v].fi << endl;
        return 0;
    }
    per(i , v , 1) {
        if(sum1 == 0) break;
        sum += a[i].fi;
        sum1--;
    }
    cout << sum << endl;
    return 0;
}


#include <bits/stdc++.h>
#include <ext/pb_ds/assoc_container.hpp>
#include <ext/pb_ds/tree_policy.hpp>
using namespace std;
using namespace __gnu_pbds;
template <typename T>
using ordered_set = tree<T,null_type, less<T>, rb_tree_tag, tree_order_statistics_node_update>;
#define SPEED ios::sync_with_stdio(false); cin.tie(0); cout.tie(0)
#define fileio freopen("in.in", "r", stdin),freopen("out.out", "w", stdout);
#define ll long long
#define ld long double
#define fi first
#define se second
#define mp make_pair
#define pb push_back
#define eb emplace_back
#define pll pair<long long ,long long >
#define ppll pair < pll , pll >
#define sd(x) scanf("%d",&x)
#define sld(x) scanf("%lld",&x)
#define INF 1e18
#define eps 0.00001
#define le length
#define debug(n1) cout << n1 << endl
#define rep(i , j , n) for(ll i = j ; i <= n ; i++)
#define per(i , j , n) for(ll i = j ; i >= n ; i--)
const ll N = 1e5 + 5;
const ll MAX = 3e5 + 5;
const ll M = 1e6 + 5;
const ll mod = 2e18 + 7;
ll MODULAR_POWER(ll a , ll b , ll MOD) {
    if(b == 0) return 1LL;
    ll d = MODULAR_POWER(a , b / 2 , MOD);
    d *= d;
    d %= MOD;
    if(b % 2) d *= a;
    d %= MOD;
    return d;
}
ll MODULAR_INVERSE(ll a , ll MOD) {
    return MODULAR_POWER(a , MOD - 2 , MOD);
}
ll BINARY_SEARCH(ll dp[] , ll n , ll key) {
    ll s = 1;
    ll e = n;
    while(s <= e) {
        ll mid = (s + e) / 2;
        if(dp[mid] == key) return mid;
        else if (dp[mid] > key) e = mid - 1;
        else s = mid + 1;
    }
    return -1;
}
string CONVERT_TO_BINARY(ll s) {
    string res = "";
    while(s != 0) {
        res += (char)('0' + s % 2);
        s /= 2;
    }
    reverse(res.begin() , res.end());
    return res;
}
bool PALINDROME(string s) {
    ll i = 0;
    ll j = s.le() - 1;
    while(i <= j) {
        if(s[i] != s[j]) return false;
        j-- , i++;
    }
}
ll n;
pll a[N];
pll b[N];
int main() {
    SPEED;
    cout.precision(8);
    cout << fixed;
    cin >> n;
    int u = 0;
    int v = 0;
    rep(i , 1 , n) {
        int x , y;
        cin >> x >> y;
        if(y > 0) {
            b[++u].fi = x;
            b[u].se = y;
        }
        else {
            a[++v].fi = x;
            a[v].se = y;
        }
    }
    sort(a + 1 , a + v + 1);
    ll sum = 0;
    ll sum1 = 0;
    rep(i , 1 , u) sum += b[i].fi;
    rep(i , 1 , u) sum1 += b[i].se - 1;
    sum1++;
    per(i , v , 1) {
        if(sum1 == 0) break;
        sum += a[i].fi;
        sum1--;
    }
    cout << sum << endl;
    return 0;
}


#include <bits/stdc++.h>
#include <ext/pb_ds/assoc_container.hpp>
#include <ext/pb_ds/tree_policy.hpp>
using namespace std;
using namespace __gnu_pbds;
template <typename T>
using ordered_set = tree<T,null_type, less<T>, rb_tree_tag, tree_order_statistics_node_update>;
#define SPEED ios::sync_with_stdio(false); cin.tie(0); cout.tie(0)
#define fileio freopen("in.in", "r", stdin),freopen("out.out", "w", stdout);
#define ll long long
#define ld long double
#define fi first
#define se second
#define mp make_pair
#define pb push_back
#define eb emplace_back
#define pll pair<long long ,long long >
#define ppll pair < pll , pll >
#define sd(x) scanf("%d",&x)
#define sld(x) scanf("%lld",&x)
#define INF 1e18
#define eps 0.00001
#define le length
#define debug(n1) cout << n1 << endl
#define rep(i , j , n) for(ll i = j ; i <= n ; i++)
#define per(i , j , n) for(ll i = j ; i >= n ; i--)
const ll N = 1e5 + 5;
const ll MAX = 3e5 + 5;
const ll M = 1e6 + 5;
const ll mod = 2e18 + 7;
ll MODULAR_POWER(ll a , ll b , ll MOD) {
    if(b == 0) return 1LL;
    ll d = MODULAR_POWER(a , b / 2 , MOD);
    d *= d;
    d %= MOD;
    if(b % 2) d *= a;
    d %= MOD;
    return d;
}
ll MODULAR_INVERSE(ll a , ll MOD) {
    return MODULAR_POWER(a , MOD - 2 , MOD);
}
ll BINARY_SEARCH(ll dp[] , ll n , ll key) {
    ll s = 1;
    ll e = n;
    while(s <= e) {
        ll mid = (s + e) / 2;
        if(dp[mid] == key) return mid;
        else if (dp[mid] > key) e = mid - 1;
        else s = mid + 1;
    }
    return -1;
}
string CONVERT_TO_BINARY(ll s) {
    string res = "";
    while(s != 0) {
        res += (char)('0' + s % 2);
        s /= 2;
    }
    reverse(res.begin() , res.end());
    return res;
}
bool PALINDROME(string s) {
    ll i = 0;
    ll j = s.le() - 1;
    while(i <= j) {
        if(s[i] != s[j]) return false;
        j-- , i++;
    }
}
ll n;
pll a[N];
pll b[N];
int main() {
    SPEED;
    cout.precision(8);
    cout << fixed;
    cin >> n;
    int u = 0;
    int v = 0;
    rep(i , 1 , n) {
        int x , y;
        cin >> x >> y;
        if(y > 0) {
            b[++u].fi = x;
            b[u].se = y;
        }
        else {
            a[++v].fi = x;
            a[v].se = y;
        }
    }
    sort(a + 1 , a + v + 1);
    ll sum = 0;
    ll sum1 = 0;
    rep(i , 1 , u) sum += b[i].fi;
    rep(i , 1 , u) sum1 += b[i].se;
    if(sum1 == 0) {
        cout << a[v].fi << endl;
        return 0;
    }
    per(i , v , 1) {
        if(sum1 == 0) break;
        sum += a[i].fi;
        sum1--;
    }
    cout << sum << endl;
    return 0;
}


#include <bits/stdc++.h>
#include <ext/pb_ds/assoc_container.hpp>
#include <ext/pb_ds/tree_policy.hpp>
using namespace std;
using namespace __gnu_pbds;
template <typename T>
using ordered_set = tree<T,null_type, less<T>, rb_tree_tag, tree_order_statistics_node_update>;
#define SPEED ios::sync_with_stdio(false); cin.tie(0); cout.tie(0)
#define fileio freopen("in.in", "r", stdin),freopen("out.out", "w", stdout);
#define ll long long
#define ld long double
#define fi first
#define se second
#define mp make_pair
#define pb push_back
#define eb emplace_back
#define pll pair<long long ,long long >
#define ppll pair < pll , pll >
#define sd(x) scanf("%d",&x)
#define sld(x) scanf("%lld",&x)
#define INF 1e18
#define eps 0.00001
#define le length
#define debug(n1) cout << n1 << endl
#define rep(i , j , n) for(ll i = j ; i <= n ; i++)
#define per(i , j , n) for(ll i = j ; i >= n ; i--)
const ll N = 1e5 + 5;
const ll MAX = 3e5 + 5;
const ll M = 1e6 + 5;
const ll mod = 2e18 + 7;
ll MODULAR_POWER(ll a , ll b , ll MOD) {
    if(b == 0) return 1LL;
    ll d = MODULAR_POWER(a , b / 2 , MOD);
    d *= d;
    d %= MOD;
    if(b % 2) d *= a;
    d %= MOD;
    return d;
}
ll MODULAR_INVERSE(ll a , ll MOD) {
    return MODULAR_POWER(a , MOD - 2 , MOD);
}
ll BINARY_SEARCH(ll dp[] , ll n , ll key) {
    ll s = 1;
    ll e = n;
    while(s <= e) {
        ll mid = (s + e) / 2;
        if(dp[mid] == key) return mid;
        else if (dp[mid] > key) e = mid - 1;
        else s = mid + 1;
    }
    return -1;
}
string CONVERT_TO_BINARY(ll s) {
    string res = "";
    while(s != 0) {
        res += (char)('0' + s % 2);
        s /= 2;
    }
    reverse(res.begin() , res.end());
    return res;
}
bool PALINDROME(string s) {
    ll i = 0;
    ll j = s.le() - 1;
    while(i <= j) {
        if(s[i] != s[j]) return false;
        j-- , i++;
    }
}
ll n;
pll a[N];
pll b[N];
int main() {
    SPEED;
    cout.precision(8);
    cout << fixed;
    cin >> n;
    int u = 0;
    int v = 0;
    rep(i , 1 , n) {
        int x , y;
        cin >> x >> y;
        if(y > 0) {
            b[++u].fi = x;
            b[u].se = y;
        }
        else {
            a[++v].fi = x;
            a[v].se = y;
        }
    }
    sort(a + 1 , a + u + 1);
    ll sum = 0;
    ll sum1 = 0;
    rep(i , 1 , u) sum += b[i].fi;
    rep(i , 1 , u) sum1 += b[i].se;
    per(i , v , 1) {
        if(sum1 == 0) break;
        sum += a[i].fi;
        sum1--;
    }
    cout << sum << endl;
    return 0;
}


#include<bits/stdc++.h>
#include <ctime>
#define hell 1000000007
#define io ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0);
#define ll long long int
using namespace std;
int maxi(ll a,ll b) {return (a>b?a:b);}
int mini(ll a,ll b) {return (a<b?a:b);}
bool sortbysec(const pair<int,int> &a,
              const pair<int,int> &b)
{
    return (a.second < b.second);
}
int main(){
	io
	int n;
	int x,y;
	cin >> n;
	if(n==1){
		cin >> x >> y;
		cout << x ;
		return 0;
	}
	int count=0,xtra=1,max=-1;

	vector < pair<int,int > > v,t;
	// vector < pair<int,int > >::iterator ir;
	vector < pair<int,int > >::reverse_iterator ir,it;

	for(int i=0;i<n;i++){
		cin >> x >> y;
		if(x>max) max=x;
		v.push_back(make_pair(x,y));
	}
	sort(v.begin(), v.end(), sortbysec);
	ir=v.rbegin();
	if(ir->second==0){
		cout << max;
		return 0;
	}
	while(ir->second!=0 && ir!=v.rend()){
		count+=ir->first;
		xtra+=ir->second-1;
		++ir;
	}
	while(ir!=v.rend()){
		t.push_back(make_pair(ir->first,ir->second));
		ir++;
	}
	it=t.rbegin();
	sort(t.begin(),t.end());
	// cout << xtra << "\n";
	while(xtra-- && it!=t.rend()){
		count+=it->first;
		it++;
		// cout << count << "\n";
	}
	cout << count;

	return 0;
}


#include<bits/stdc++.h>
#include <ctime>
#define hell 1000000007
#define io ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0);
#define ll long long int
using namespace std;
int maxi(ll a,ll b) {return (a>b?a:b);}
int mini(ll a,ll b) {return (a<b?a:b);}
bool sortbysec(const pair<int,int> &a,
              const pair<int,int> &b)
{
    return (a.second < b.second);
}
int main(){
	io
	int n;
	int x,y;
	cin >> n;
	if(n==1){
		cin >> x >> y;
		cout << x ;
		return 0;
	}
	int count=0,xtra=1,max=-1;

	vector < pair<int,int > > v,t;
	// vector < pair<int,int > >::iterator ir;
	vector < pair<int,int > >::reverse_iterator ir,it;

	for(int i=0;i<n;i++){
		cin >> x >> y;
		if(x>max) max=x;
		v.push_back(make_pair(x,y));
	}
	sort(v.begin(), v.end(), sortbysec);
	ir=v.rbegin();
	if(ir->second==0){
		cout << max;
		return 0;
	}
	while(ir->second!=0 && ir!=v.rend()){
		count+=ir->first;
		xtra+=ir->second-1;
		++ir;
	}
	while(ir!=v.rend()){
		t.push_back(make_pair(ir->first,ir->second));
		ir++;
	}
	it=t.rbegin();
	sort(t.begin(),t.end());
	// cout << xtra << "\n";
	while(xtra-=1 && it!=t.rend()){
		count+=it->first;
		it++;
		// cout << count << "\n";
	}
	cout << count;

	return 0;
}


#include<bits/stdc++.h>
#include <ctime>
#define hell 1000000007
#define io ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0);
#define ll long long int
using namespace std;
int maxi(ll a,ll b) {return (a>b?a:b);}
int mini(ll a,ll b) {return (a<b?a:b);}
bool sortbysec(const pair<int,int> &a,
              const pair<int,int> &b)
{
    return (a.second < b.second);
}
int main(){
	io
	int n;
	int x,y;
	cin >> n;
	if(n==1){
		cin >> x >> y;
		cout << x ;
		return 0;
	}
	int count=0,xtra=1,max=-1;

	vector < pair<int,int > > v,t;
	// vector < pair<int,int > >::iterator ir;
	vector < pair<int,int > >::reverse_iterator ir,it;

	for(int i=0;i<n;i++){
		cin >> x >> y;
		if(x>max) max=x;
		v.push_back(make_pair(x,y));
	}
	sort(v.begin(), v.end(), sortbysec);
	ir=v.rbegin();
	if(ir->second==0){
		cout << max;
		return 0;
	}
	while(ir->second!=0){
		count+=ir->first;
		xtra+=ir->second-1;
		++ir;
	}
	while(ir!=v.rend()){
		t.push_back(make_pair(ir->first,ir->second));
		ir++;
	}
	it=t.rbegin();
	sort(t.begin(),t.end());
	// cout << xtra << "\n";
	while(xtra--){
		count+=it->first;
		it++;
		// cout << count << "\n";
	}
	cout << count;

	return 0;
}


#include<bits/stdc++.h>
#include <ctime>
#define hell 1000000007
#define io ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0);
#define ll long long int
using namespace std;
int maxi(ll a,ll b) {return (a>b?a:b);}
int mini(ll a,ll b) {return (a<b?a:b);}
bool sortbysec(const pair<int,int> &a,
              const pair<int,int> &b)
{
    return (a.second < b.second);
}
int main(){
	io
	int n;
	cin >> n;
	int count=0,xtra=1,max=-1;
	int x,y;
	vector < pair<int,int > > v,t;
	// vector < pair<int,int > >::iterator ir;
	vector < pair<int,int > >::reverse_iterator ir,it;

	for(int i=0;i<n;i++){
		cin >> x >> y;
		if(x>max) max=x;
		v.push_back(make_pair(x,y));
	}
	sort(v.begin(), v.end(), sortbysec);
	ir=v.rbegin();
	if(ir->second==0){
		cout << max;
		return 0;
	}
	while(ir->second!=0){
		count+=ir->first;
		xtra+=ir->second-1;
		++ir;
	}
	while(ir!=v.rend()){
		t.push_back(make_pair(ir->first,ir->second));
		ir++;
	}
	it=t.rbegin();
	sort(t.begin(),t.end());
	// cout << xtra << "\n";
	while(xtra--){
		count+=it->first;
		it++;
		// cout << count << "\n";
	}
	cout << count;

	return 0;
}


#include<bits/stdc++.h>
#include <ctime>
#define hell 1000000007
#define io ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0);
#define ll long long int
using namespace std;
int maxi(ll a,ll b) {return (a>b?a:b);}
int mini(ll a,ll b) {return (a<b?a:b);}
bool sortbysec(const pair<int,int> &a,
              const pair<int,int> &b)
{
    return (a.second < b.second);
}
int main(){
	io
	int n;
	int x,y;
	cin >> n;
	if(n==1){
		cin >> x >> y;
		cout << x ;
		return 0;
	}
	int count=0,xtra=1,max=-1;

	vector < pair<int,int > > v,t;
	// vector < pair<int,int > >::iterator ir;
	vector < pair<int,int > >::reverse_iterator ir,it;

	for(int i=0;i<n;i++){
		cin >> x >> y;
		if(x>max) max=x;
		v.push_back(make_pair(x,y));
	}
	sort(v.begin(), v.end(), sortbysec);
	ir=v.rbegin();
	if(ir->second==0){
		cout << max;
		return 0;
	}
	while(ir->second!=0 && ir!=v.rend()){
		count+=ir->first;
		xtra+=ir->second-1;
		++ir;
	}
	while(ir!=v.rend()){
		t.push_back(make_pair(ir->first,ir->second));
		ir++;
	}
	it=t.rbegin();
	sort(t.begin(),t.end());
	// cout << xtra << "\n";
	while(xtra--){
		count+=it->first;
		it++;
		// cout << count << "\n";
	}
	cout << count;

	return 0;
}


#include <bits/stdc++.h>

#define F first
#define S second
#define pb push_back
#define ll long long

using namespace std;

const ll inf=1e18;
const int mod=1e9+7;

pair <int,int> a[1000];

bool f1 (pair <int,int> a, pair <int,int> b){
  return a.S > b.S;
}
bool f2 (pair <int,int> a, pair <int,int> b){
  return a.S == b.S && a.F > b.F;

}

int main() {
    ios_base::sync_with_stdio(0);
   // freopen("input.txt", "r", stdin);
   // freopen("output.txt", "w", stdout);
    int n;
    cin >> n;
    for (int i = 0;i<n;i++){
        cin >> a[i].F >> a[i].S;
    }
    sort(a,a+n,f1);
    sort(a,a+n,f2);
    int j = 0, k = 0 , ans = 0;
    while (a[j].S > 0){
        k += a[j].S;
        ans += a[j].F;
        j++;
    }
    k -= j;
    if (j == 0){
        int mx = 0;
        for (int i = 0; i < n; i++){
            if (a[i].F > mx){
                mx = a[i].F;
            }
        }
        cout << mx << endl;
        return 0;
    }
    for (int i = j; i < min(n,j + k + 1);i++){
        ans += a[i].F;
    }
    cout << ans << endl;
}


#include <bits/stdc++.h>

#define F first
#define S second
#define pb push_back
#define ll long long

using namespace std;

const ll inf=1e18;
const int mod=1e9+7;

pair <int,int> a[1000];

bool f1 (pair <int,int> a, pair <int,int> b){
  return a.S > b.S;
}
bool f2 (pair <int,int> a, pair <int,int> b){
  return a.S == b.S && a.F > b.F;

}

int main() {
    ios_base::sync_with_stdio(0);
    //freopen("input.txt", "r", stdin);
    //freopen("output.txt", "w", stdout);
    int n;
    cin >> n;
    for (int i = 0;i<n;i++){
        cin >> a[i].F >> a[i].S;
    }
    sort(a,a+n,f1);
    sort(a,a+n,f2);
    int j = 0, k = 0 , ans = 0;
    while (a[j].S > 0){
        k += a[j].S;
        ans += a[j].F;
        j++;
    }
    if (j == 0){
        int mx = 0;
        for (int i = 0; i < n; i++){
            if (a[i].F > mx){
                mx = a[i].F;
            }
        }
        cout << mx << endl;
        return 0;
    }
    for (int i = j; i < min(n,j + k);i++){
        ans += a[i].F;
    }
    cout << ans << endl;
}


#include <bits/stdc++.h>

#define F first
#define S second
#define pb push_back
#define ll long long

using namespace std;

const ll inf=1e18;
const int mod=1e9+7;

pair <int,int> a[1000];

bool f1 (pair <int,int> a, pair <int,int> b){
  return a.S > b.S;
}
bool f2 (pair <int,int> a, pair <int,int> b){
  return a.S >= b.S && a.F > b.F;

}

int main() {
    ios_base::sync_with_stdio(0);
    //freopen("input.txt", "r", stdin);
    //freopen("output.txt", "w", stdout);
    int n;
    cin >> n;
    for (int i = 0;i<n;i++){
        cin >> a[i].F >> a[i].S;
    }
    sort(a,a+n,f1);
    sort(a,a+n,f2);
    int j = 0, k = 0 , ans = 0;
    while (a[j].S > 0){
        k += a[j].S;
        ans += a[j].F;
        j++;
    }
    k -= j;
    if (j == 0){
        int mx = 0;
        for (int i = 0; i < n; i++){
            if (a[i].F > mx){
                mx = a[i].F;
            }
        }
        cout << mx << endl;
        return 0;
    }
    for (int i = j; i < min(n,j + k + 1);i++){
        ans += a[i].F;
    }
    cout << ans << endl;
}


#include <bits/stdc++.h>

#define F first
#define S second
#define pb push_back
#define ll long long

using namespace std;

const ll inf=1e18;
const int mod=1e9+7;

pair <int,int> a[1000];

bool f1 (pair <int,int> a, pair <int,int> b){
  if (a.S == b.S) return a.F > b.F;
  else return a.S > b.S;
}

int main() {
    ios_base::sync_with_stdio(0);
    //freopen("input.txt", "r", stdin);
   //freopen("output.txt", "w", stdout);
    int n;
    cin >> n;
    for (int i = 0;i<n;i++){
        cin >> a[i].F >> a[i].S;
    }
    sort(a,a+n,f1);
    for (int i = 0; i < n ; i ++){
        cout << a[i].F << " " << a[i].S << endl;
    }
    int j = 0, k = 0 , ans = 0;
    while (a[j].S > 0){
        k += a[j].S;
        ans += a[j].F;
        j++;
    }
    k -= j;
    if (j == 0){
        int mx = 0;
        for (int i = 0; i < n; i++){
            if (a[i].F > mx){
                mx = a[i].F;
            }
        }
        cout << mx << endl;
        return 0;
    }
    for (int i = j; i < min(n,j + k + 1);i++){
        ans += a[i].F;
    }
    cout << ans << endl;
}


#include <bits/stdc++.h>

#define F first
#define S second
#define pb push_back
#define ll long long

using namespace std;

const ll inf=1e18;
const int mod=1e9+7;

pair <int,int> a[1000];

bool f1 (pair <int,int> a, pair <int,int> b){
  if (a.S == b.S) return a.F > b.F;
  else return a.S > b.S;
}

int main() {
    ios_base::sync_with_stdio(0);
    //freopen("input.txt", "r", stdin);
   //freopen("output.txt", "w", stdout);
    int n;
    cin >> n;
    for (int i = 0;i<n;i++){
        cin >> a[i].F >> a[i].S;
    }
    sort(a,a+n,f1);
//    for (int i = 0; i < n ; i ++){
//        cout << a[i].F << " " << a[i].S << endl;
//    }
    int j = 0, k = 0 , ans = 0;
    while (a[j].S > 0){
        k += a[j].S;
        ans += a[j].F;
        j++;
    }
    k -= j;
    if (j == 0){
        int mx = 0;
        for (int i = 0; i < n; i++){
            if (a[i].F > mx){
                mx = a[i].F;
            }
        }
        cout << mx << endl;
        return 0;
    }
    for (int i = j; i < min(n,j + k + 1);i++){
        ans += a[i].F;
    }
    cout << ans << endl;
}


#include <bits/stdc++.h>

#define F first
#define S second
#define pb push_back
#define ll long long

using namespace std;

const ll inf=1e18;
const int mod=1e9+7;

pair <int,int> a[1000];

bool f1 (pair <int,int> a, pair <int,int> b){
  return a.S > b.S;
}
bool f2 (pair <int,int> a, pair <int,int> b){
  return a.S >= b.S && a.F > b.F;

}

int main() {
    ios_base::sync_with_stdio(0);
    //freopen("input.txt", "r", stdin);
    //freopen("output.txt", "w", stdout);
    int n;
    cin >> n;
    for (int i = 0;i<n;i++){
        cin >> a[i].F >> a[i].S;
    }
    sort(a,a+n,f1);
    sort(a,a+n,f2);
    for (int i = 0; i < n ; i ++){
        cout << a[i].F << " " << a[i].S << endl;
    }
    int j = 0, k = 0 , ans = 0;
    while (a[j].S > 0){
        k += a[j].S;
        ans += a[j].F;
        j++;
    }
    k -= j;
    if (j == 0){
        int mx = 0;
        for (int i = 0; i < n; i++){
            if (a[i].F > mx){
                mx = a[i].F;
            }
        }
        cout << mx << endl;
        return 0;
    }
    for (int i = j; i < min(n,j + k + 1);i++){
        ans += a[i].F;
    }
    cout << ans << endl;
}


#include <bits/stdc++.h>

#define F first
#define S second
#define pb push_back
#define ll long long

using namespace std;

const ll inf=1e18;
const int mod=1e9+7;

pair <int,int> a[1000];

bool f1 (pair <int,int> a, pair <int,int> b){
  return a.S > b.S;
}
bool f2 (pair <int,int> a, pair <int,int> b){
  return a.S >= b.S && a.F > b.F;

}

int main() {
    ios_base::sync_with_stdio(0);
    //freopen("input.txt", "r", stdin);
   // freopen("output.txt", "w", stdout);
    int n;
    cin >> n;
    for (int i = 0;i<n;i++){
        cin >> a[i].F >> a[i].S;
    }
    sort(a,a+n,f1);
    sort(a,a+n,f2);
    int j = 0, k = 0 , ans = 0;
    while (a[j].S > 0){
        k += a[j].S;
        ans += a[j].F;
        j++;
    }
    k -= j;
    if (j == 0){
        int mx = 0;
        for (int i = 0; i < n; i++){
            if (a[i].F > mx){
                mx = a[i].F;
            }
        }
        cout << mx << endl;
        return 0;
    }
    for (int i = j; i < min(n,j + k + 1);i++){
        ans += a[i].F;
    }
    cout << ans << endl;
}


#include <iostream>
#include<algorithm>
#include<vector>
#include<string>
#include<map>
using namespace std;
int main()
{
	int n;
	cin>> n;
	vector <pair <int,int> >v(n);
	long long int ans=0;

	for (int i = 0; i < n; i++) {
		cin >> v[i].second >> v[i].first ;
	}

	sort(v.begin(), v.end(),greater<pair<int,int> >());

	/*for (int i = 0; i < n; i++) {
		cout << v[i].first << v[i].second <<endl;
	}*/

		ans += v[0].second;
		for (int l = 1; l <= v[0].first; l++) {
			v[0].first += v[l].first;
			ans += v[l].second;
		}
	cout << ans;

}


#include <iostream>
#include<algorithm>
#include<vector>
#include<string>
#include<map>
using namespace std;
int main()
{
	int n;
	cin>> n;
	vector <pair <long long int,long long int> >v(n);
	long long int ans=0;

	for (int i = 0; i < n; i++) {
		cin >> v[i].second >> v[i].first ;
	}

	sort(v.begin(), v.end(),greater<pair<long long int,long long int> >());

	/*for (int i = 0; i < n; i++) {
		cout << v[i].first << v[i].second <<endl;
	}*/

		ans += v[0].second;
		long long int c= v[0].first;
		for (int l = 1; l <= c; l++) {
			 c+= v[l].first;
			ans += v[l].second;
		}
	cout << ans;

}


#include <iostream>
#include<algorithm>
#include<vector>
#include<string>
#include<map>
using namespace std;
int main()
{
	int n;
	cin >> n;
	vector <pair <int, int> >v(n);
	long long int ans = 0;

	for (int i = 0; i < n; i++) {
		cin >> v[i].second >> v[i].first;
	}

	sort(v.begin(), v.end(), greater<pair<int, int> >());

	/*for (int i = 0; i < n; i++) {
		cout << v[i].first << v[i].second <<endl;
	}*/

	ans += v[0].second;
	for (int l = 1; l <= v[0].first && v[0].first<=n-1; l++) {
		v[0].first += v[l].first;
		ans += v[l].second;
	}
	cout << ans;

}


#include <iostream>
#include<algorithm>
#include<vector>
#include<string>
#include<map>
using namespace std;
int main()
{
	int n;
	cin >> n;
	vector <pair <int, int> >v(n);
	long long int ans = 0;

	for (int i = 0; i < n; i++) {
		cin >> v[i].second >> v[i].first;
	}

	sort(v.begin(), v.end(), greater<pair<int, int> >());

	/*for (int i = 0; i < n; i++) {
		cout << v[i].first << v[i].second <<endl;
	}*/

	ans += v[0].second;
	for (int l = 1; l <= v[0].first && l<=n-1; l++) {

		v[0].first += v[l].first;
		ans += v[l].second;
	}
	cout << ans;

}


#include <iostream>
#include<algorithm>
#include<vector>
#include<string>
#include<map>
using namespace std;
int main()
{
	int n;
	cin>> n;
	vector <pair <long long int,int> >v(n);
	long long int ans=0;

	for (int i = 0; i < n; i++) {
		cin >> v[i].second >> v[i].first ;
	}

	sort(v.begin(), v.end(),greater<pair<int,int> >());

	/*for (int i = 0; i < n; i++) {
		cout << v[i].first << v[i].second <<endl;
	}*/

		ans += v[0].second;
		for (int l = 1; l <= v[0].first; l++) {
			v[0].first += v[l].first;
			ans += v[l].second;
		}
	cout << ans;

}


#include <iostream>
#include<algorithm>
#include<vector>
#include<string>
#include<map>
using namespace std;
int main()
{
	int n;
	cin>> n;
	vector <pair <int,int> >v(n);
	long long int ans=0;

	for (int i = 0; i < n; i++) {
		cin >> v[i].second >> v[i].first ;
	}

	sort(v.begin(), v.end(),greater<pair<int,int> >());

	/*for (int i = 0; i < n; i++) {
		cout << v[i].first << v[i].second <<endl;
	}*/

		ans += v[0].second;
		long long int c= v[0].first;
		for (int l = 1; l <= c; l++) {
			 c+= v[l].first;
			ans += v[l].second;
		}
	cout << ans;

}


/// Bismillahir Rahmanir Rahim
/* Mohammad Morsalin
   Dept of ICE, NSTU
*/
#include<bits/stdc++.h>
#include <ext/pb_ds/assoc_container.hpp>
#include <ext/pb_ds/tree_policy.hpp>
using namespace __gnu_pbds;
#define ll long long
#define pb push_back
#define mp make_pair
#define endl "\n"
#define int long long
#define f0(n) for(int i=0;i<n;i++)
#define ms(x) memset(x,0,sizeof(x))
#define ms2d(x,m,n) memset(x, 0, sizeof(x[0][0]) * m * n)
#define uniq(vec) vec.resize(distance(vec.begin(),unique(vec.begin(),vec.end())))
#define ordered_set tree<int, null_type,less<int>, rb_tree_tag,tree_order_statistics_node_update>
#define pi pair<int,int>
#define tc(t) int t;cin>>t;while(t--)
#define bits(n) __builtin_popcount(n)
#define maxpq priority_queue<int>
#define minpq priority_queue<int, vector<int>, greater<int> >
#define ins insert
#define ALL(v) v.begin(),v.end()
#define highest(x) numeric_limits<x>::max()
#define lowest(x) numeric_limits<x>::min()
#define Inf INFINITY
#define minv(v) *min_element(v.begin(),v.end())
#define maxv(v) *max_element(v.begin(),v.end())
#define fi first
#define se second
#define PI acos(-1)
#define sz(a) (int)a.size();
#define IOS ios::sync_with_stdio(false);
using namespace std;
int gcd(int a, int b) { if (a == 0) return b; return gcd(b % a, a);}
//typedef tree<pair<int, int>,null_type,less<pair<int, int>>,rb_tree_tag,tree_order_statistics_node_update> ordered_multiset;
int dx8[] = {0, 0, 1, 1, 1, -1, -1, -1};
int dy8[] = {1,-1, 1, -1, 0, 0, -1, 1};
int dx4[] = {0, 0, 1, -1};
int dy4[] = {1, -1, 0, 0};
const long long MOD = 1000000007;
double sq(double x) {return x*x;}
template<typename T>inline T Bigmod(T base, T power, T MOD){
    T ret=1;
    while(power)
    {
        if(power & 1)ret=(ret*base)%MOD;
        base=(base*base)%MOD;
        power>>=1;
    }
    return ret;
}

bool sortinrev(const pair<int,int> &a,
               const pair<int,int> &b)
{
		if(a.first==b.first) return (a.se>b.se);
       	return (a.first > b.first);
}
signed main()
{
    IOS
    int n;
    while(cin>>n){
    	vector<pair<int,int> > vp;
    	for(int i=0;i<n;i++){
    		int a,b;
    		cin>>a>>b;
    		vp.pb(mp(b,a));
		}
		sort(ALL(vp),sortinrev);
		int cnt=0;
		int ans=0;
		stack<int>st;
		st.push(0);
		while(!st.empty()){
			int ind=st.top();
			st.pop();
			ans+=vp[ind].se;
			for(int i=cnt;i<cnt+vp[ind].fi && i<n;i++){
				st.push(i);
				//cout << i << endl;
			}
			cnt+=vp[ind].fi;
			cnt=min(cnt,n-1);
		}
		cout << ans << endl;
	}
    return 0;
}
///Alhamdulillah


/// Bismillahir Rahmanir Rahim
/* Mohammad Morsalin
   Dept of ICE, NSTU
*/
#include<bits/stdc++.h>
#include <ext/pb_ds/assoc_container.hpp>
#include <ext/pb_ds/tree_policy.hpp>
using namespace __gnu_pbds;
#define ll long long
#define pb push_back
#define mp make_pair
#define endl "\n"
#define int long long
#define f0(n) for(int i=0;i<n;i++)
#define ms(x) memset(x,0,sizeof(x))
#define ms2d(x,m,n) memset(x, 0, sizeof(x[0][0]) * m * n)
#define uniq(vec) vec.resize(distance(vec.begin(),unique(vec.begin(),vec.end())))
#define ordered_set tree<int, null_type,less<int>, rb_tree_tag,tree_order_statistics_node_update>
#define pi pair<int,int>
#define tc(t) int t;cin>>t;while(t--)
#define bits(n) __builtin_popcount(n)
#define maxpq priority_queue<int>
#define minpq priority_queue<int, vector<int>, greater<int> >
#define ins insert
#define ALL(v) v.begin(),v.end()
#define highest(x) numeric_limits<x>::max()
#define lowest(x) numeric_limits<x>::min()
#define Inf INFINITY
#define minv(v) *min_element(v.begin(),v.end())
#define maxv(v) *max_element(v.begin(),v.end())
#define fi first
#define se second
#define PI acos(-1)
#define sz(a) (int)a.size();
#define IOS ios::sync_with_stdio(false);
using namespace std;
int gcd(int a, int b) { if (a == 0) return b; return gcd(b % a, a);}
//typedef tree<pair<int, int>,null_type,less<pair<int, int>>,rb_tree_tag,tree_order_statistics_node_update> ordered_multiset;
int dx8[] = {0, 0, 1, 1, 1, -1, -1, -1};
int dy8[] = {1,-1, 1, -1, 0, 0, -1, 1};
int dx4[] = {0, 0, 1, -1};
int dy4[] = {1, -1, 0, 0};
const long long MOD = 1000000007;
double sq(double x) {return x*x;}
template<typename T>inline T Bigmod(T base, T power, T MOD){
    T ret=1;
    while(power)
    {
        if(power & 1)ret=(ret*base)%MOD;
        base=(base*base)%MOD;
        power>>=1;
    }
    return ret;
}

bool sortinrev(const pair<int,int> &a,
               const pair<int,int> &b)
{
		if(a.first==b.first) return (a.se>b.se);
       	return (a.first > b.first);
}
signed main()
{
    IOS
    int n;
    while(cin>>n){
    	vector<pair<int,int> > vp;
    	for(int i=0;i<n;i++){
    		int a,b;
    		cin>>a>>b;
    		vp.pb(mp(b,a));
		}
		sort(ALL(vp),sortinrev);
		int cnt=0;
		int ans=0;
		stack<int>st;
		st.push(0);
		while(!st.empty()){
			int ind=st.top();
			st.pop();
			ans+=vp[ind].se;
			for(int i=0;i<vp[ind].fi;i++){
				cnt++;
				if(cnt==n)continue;
				st.push(cnt);
				//cout << i << endl;
			}
		}
		cout << ans << endl;
	}
    return 0;
}
///Alhamdulillah


/// Bismillahir Rahmanir Rahim
/* Mohammad Morsalin
   Dept of ICE, NSTU
*/
#include<bits/stdc++.h>
#include <ext/pb_ds/assoc_container.hpp>
#include <ext/pb_ds/tree_policy.hpp>
using namespace __gnu_pbds;
#define ll long long
#define pb push_back
#define mp make_pair
#define endl "\n"
#define int long long
#define f0(n) for(int i=0;i<n;i++)
#define ms(x) memset(x,0,sizeof(x))
#define ms2d(x,m,n) memset(x, 0, sizeof(x[0][0]) * m * n)
#define uniq(vec) vec.resize(distance(vec.begin(),unique(vec.begin(),vec.end())))
#define ordered_set tree<int, null_type,less<int>, rb_tree_tag,tree_order_statistics_node_update>
#define pi pair<int,int>
#define tc(t) int t;cin>>t;while(t--)
#define bits(n) __builtin_popcount(n)
#define maxpq priority_queue<int>
#define minpq priority_queue<int, vector<int>, greater<int> >
#define ins insert
#define ALL(v) v.begin(),v.end()
#define highest(x) numeric_limits<x>::max()
#define lowest(x) numeric_limits<x>::min()
#define Inf INFINITY
#define minv(v) *min_element(v.begin(),v.end())
#define maxv(v) *max_element(v.begin(),v.end())
#define fi first
#define se second
#define PI acos(-1)
#define sz(a) (int)a.size();
#define IOS ios::sync_with_stdio(false);
using namespace std;
int gcd(int a, int b) { if (a == 0) return b; return gcd(b % a, a);}
//typedef tree<pair<int, int>,null_type,less<pair<int, int>>,rb_tree_tag,tree_order_statistics_node_update> ordered_multiset;
int dx8[] = {0, 0, 1, 1, 1, -1, -1, -1};
int dy8[] = {1,-1, 1, -1, 0, 0, -1, 1};
int dx4[] = {0, 0, 1, -1};
int dy4[] = {1, -1, 0, 0};
const long long MOD = 1000000007;
double sq(double x) {return x*x;}
template<typename T>inline T Bigmod(T base, T power, T MOD){
    T ret=1;
    while(power)
    {
        if(power & 1)ret=(ret*base)%MOD;
        base=(base*base)%MOD;
        power>>=1;
    }
    return ret;
}

bool sortinrev(const pair<int,int> &a,
               const pair<int,int> &b)
{
		if(a.first==b.first) return (a.se>b.se);
       	return (a.first > b.first);
}
signed main()
{
    IOS
    int n;
    while(cin>>n){
    	vector<pair<int,int> > vp;
    	for(int i=0;i<n;i++){
    		int a,b;
    		cin>>a>>b;
    		vp.pb(mp(b,a));
		}
		sort(ALL(vp),sortinrev);
		int cnt=0;
		int ans=0;
		for(int i=0;i<n;i++){
			if(i>cnt)break;
			cnt+=vp[i].fi;
			ans+=vp[i].se;
		}
		cout << ans << endl;
	}
    return 0;
}
///Alhamdulillah


/// Bismillahir Rahmanir Rahim
/* Mohammad Morsalin
   Dept of ICE, NSTU
*/
#include<bits/stdc++.h>
#include <ext/pb_ds/assoc_container.hpp>
#include <ext/pb_ds/tree_policy.hpp>
using namespace __gnu_pbds;
#define ll long long
#define pb push_back
#define mp make_pair
#define endl "\n"
#define int long long
#define f0(n) for(int i=0;i<n;i++)
#define ms(x) memset(x,0,sizeof(x))
#define ms2d(x,m,n) memset(x, 0, sizeof(x[0][0]) * m * n)
#define uniq(vec) vec.resize(distance(vec.begin(),unique(vec.begin(),vec.end())))
#define ordered_set tree<int, null_type,less<int>, rb_tree_tag,tree_order_statistics_node_update>
#define pi pair<int,int>
#define tc(t) int t;cin>>t;while(t--)
#define bits(n) __builtin_popcount(n)
#define maxpq priority_queue<int>
#define minpq priority_queue<int, vector<int>, greater<int> >
#define ins insert
#define ALL(v) v.begin(),v.end()
#define highest(x) numeric_limits<x>::max()
#define lowest(x) numeric_limits<x>::min()
#define Inf INFINITY
#define minv(v) *min_element(v.begin(),v.end())
#define maxv(v) *max_element(v.begin(),v.end())
#define fi first
#define se second
#define PI acos(-1)
#define sz(a) (int)a.size();
#define IOS ios::sync_with_stdio(false);
using namespace std;
int gcd(int a, int b) { if (a == 0) return b; return gcd(b % a, a);}
//typedef tree<pair<int, int>,null_type,less<pair<int, int>>,rb_tree_tag,tree_order_statistics_node_update> ordered_multiset;
int dx8[] = {0, 0, 1, 1, 1, -1, -1, -1};
int dy8[] = {1,-1, 1, -1, 0, 0, -1, 1};
int dx4[] = {0, 0, 1, -1};
int dy4[] = {1, -1, 0, 0};
const long long MOD = 1000000007;
double sq(double x) {return x*x;}
template<typename T>inline T Bigmod(T base, T power, T MOD){
    T ret=1;
    while(power)
    {
        if(power & 1)ret=(ret*base)%MOD;
        base=(base*base)%MOD;
        power>>=1;
    }
    return ret;
}

bool sortinrev(const pair<int,int> &a,
               const pair<int,int> &b)
{
		if(a.first==b.first) return (a.se>b.se);
       	return (a.first > b.first);
}
signed main()
{
    IOS
    int n;
    while(cin>>n){
    	vector<pair<int,int> > vp;
    	for(int i=0;i<n;i++){
    		int a,b;
    		cin>>a>>b;
    		vp.pb(mp(b,a));
		}
		sort(ALL(vp),sortinrev);
		int cnt=0;
		int ans=0;
		stack<int>st;
		st.push(0);
		while(!st.empty()){
			int ind=st.top();
			st.pop();
			ans+=vp[ind].se;
			for(int i=cnt+1;i<cnt+vp[ind].fi && i<n;i++){
				st.push(i);
				//cout << i << endl;
			}
			cnt+=vp[ind].fi;
			cnt=min(cnt,n-1);
		}
		cout << ans << endl;
	}
    return 0;
}
///Alhamdulillah


// Author:: MUKUL KUMAR RAI
// Institution:: Jalpaiguri Government Engineering College
//If you are not doing well now just stick to it and learn new things one day you will be...
//Compete with yourself
#include<bits/stdc++.h>
using namespace std;
#define ll long long int
#define ld long double
#define fi first
#define se second
#define pb push_back
///*template{{{
#define sz(x) (ll)x.size()
#define all(x) (x.begin(),x.end())
#define trav(a,x) for(auto &a:x)
#define fr(i,a,b)  for(ll i=a;i<=b;i++)
#define fr1(i,a)   for(ll i=0;i<a;i++)
#define frr(i,a,b) for(ll i=b;i>=a;i--)
#define frr1(i,a)   for(ll i=a-1;i>=0;i--)
#define sorta(a,n) sort(a,a+n)
#define sortd(a,n) sort(a,a+n,greater<ll>())
#define sortva(a) sort(a.begin(),a.end())
#define sortvd(a) sort(a.begin(),a.end(),greater<ll>())
#define tc(t) while(t--)
#define fio ios_base::sync_with_stdio(false);cin.tie(NULL);
using vi= vector<ll>;
using vvi= vector<vi>;
using vb =vector<bool>;
using vc =vector<char>;
using vs =vector<string>;
using vld =vector<ld>;
using pii =pair<ll,ll>;
using psi =pair<string,ll>;
using pci =pair<char,ll>;
using vpii =vector<pii>;
//}}}template*/
ll mod=1e9+7;
ll const maxn=1e5+5;
ll const inf=1e18;
bool ss(const pair<ll,ll> &a, const pair<ll,ll> &b) {
    if(a.first>b.first)
    return a.first>b.first;
    if(a.first==b.first)
    return a.second>b.second;
    return a.first>b.first;
}
ll add(ll a,ll b){
    return ((a%mod)+(b%mod))%mod;
}
ll mul(ll a,ll b){
    return ((a%mod)*(b%mod))%mod;
}
ll powm(ll x,ll n,ll M)
{
    ll result=1;
    while(n>0)
    {
        if(n % 2 ==1)
            result=(result * x)%M;
        x=(x*x)%M;
        n=n/2;
    }
    return result;
}
ll modinverse(ll a, ll m){
    return powm(a,m-2,m);
}
bool prime(ll x){
    if(x<=1)return false;
    for(int i=2;i<=sqrt(x);i++)if(x%i==0)return false;
    return true;
}
ll divisor(ll x){
    ll cnt=0;
    for(int i=1;i<=sqrt(x);i++){
        if(x%i==0){
            if(i!=x/i)cnt+=2;
            else cnt+=1;
        }
    }
    return cnt;
}
vector<ll> sieve(ll n) {
    bool prim[n+1];
    memset(prim, true, sizeof(prim));

    for (ll p=2; p*p<=n; p++) {
        if (prim[p] == true) {
            for (int i=p*p; i<=n; i += p)
                prim[i] = false;
        }
    }
    vector<ll>v;
    for(int i=2;i<=n;i++)if(prim[i])v.push_back(i);
    return v;
}
int main(){
    #ifndef ONLINE_JUDGE
    freopen("input.txt","r",stdin);
    freopen("output.txt","w",stdout);
    #endif
    fio;
    vpii v;
    ll n;
    cin>>n;
    fr1(i,n){
        ll x,y;
        cin>>x>>y;
        v.pb({y,x});
    }
    sort(v.begin(),v.end(),ss);
    fr1(i,n)cout<<v[i].fi<<" "<<v[i].se<<"\n";
    ll i=1;
    ll ans=0;
    ll cnt=v[0].fi;
    while(cnt>=i and cnt<=n){
        if(cnt+v[i].fi>=i)cnt+=v[i].fi;
        i++;
    }
    fr1(i,min(cnt+1,n))ans+=v[i].se;
    //cout<<cnt<<"\n";
    cout<<ans;
    return 0;
}


// Author:: MUKUL KUMAR RAI
// Institution:: Jalpaiguri Government Engineering College
//If you are not doing well now just stick to it and learn new things one day you will be...
//Compete with yourself
#include<bits/stdc++.h>
using namespace std;
#define ll long long int
#define ld long double
#define fi first
#define se second
#define pb push_back
///*template{{{
#define sz(x) (ll)x.size()
#define all(x) (x.begin(),x.end())
#define trav(a,x) for(auto &a:x)
#define fr(i,a,b)  for(ll i=a;i<=b;i++)
#define fr1(i,a)   for(ll i=0;i<a;i++)
#define frr(i,a,b) for(ll i=b;i>=a;i--)
#define frr1(i,a)   for(ll i=a-1;i>=0;i--)
#define sorta(a,n) sort(a,a+n)
#define sortd(a,n) sort(a,a+n,greater<ll>())
#define sortva(a) sort(a.begin(),a.end())
#define sortvd(a) sort(a.begin(),a.end(),greater<ll>())
#define tc(t) while(t--)
#define fio ios_base::sync_with_stdio(false);cin.tie(NULL);
using vi= vector<ll>;
using vvi= vector<vi>;
using vb =vector<bool>;
using vc =vector<char>;
using vs =vector<string>;
using vld =vector<ld>;
using pii =pair<ll,ll>;
using psi =pair<string,ll>;
using pci =pair<char,ll>;
using vpii =vector<pii>;
//}}}template*/
ll mod=1e9+7;
ll const maxn=1e5+5;
ll const inf=1e18;
bool ss(const pair<ll,ll> &a, const pair<ll,ll> &b) {
    if(a.first>b.first)
    return a.first>b.first;
    if(a.first==b.first)
    return a.second>b.second;
    return a.first>b.first;
}
ll add(ll a,ll b){
    return ((a%mod)+(b%mod))%mod;
}
ll mul(ll a,ll b){
    return ((a%mod)*(b%mod))%mod;
}
ll powm(ll x,ll n,ll M)
{
    ll result=1;
    while(n>0)
    {
        if(n % 2 ==1)
            result=(result * x)%M;
        x=(x*x)%M;
        n=n/2;
    }
    return result;
}
ll modinverse(ll a, ll m){
    return powm(a,m-2,m);
}
bool prime(ll x){
    if(x<=1)return false;
    for(int i=2;i<=sqrt(x);i++)if(x%i==0)return false;
    return true;
}
ll divisor(ll x){
    ll cnt=0;
    for(int i=1;i<=sqrt(x);i++){
        if(x%i==0){
            if(i!=x/i)cnt+=2;
            else cnt+=1;
        }
    }
    return cnt;
}
vector<ll> sieve(ll n) {
    bool prim[n+1];
    memset(prim, true, sizeof(prim));

    for (ll p=2; p*p<=n; p++) {
        if (prim[p] == true) {
            for (int i=p*p; i<=n; i += p)
                prim[i] = false;
        }
    }
    vector<ll>v;
    for(int i=2;i<=n;i++)if(prim[i])v.push_back(i);
    return v;
}
int main(){
    #ifndef ONLINE_JUDGE
    freopen("input.txt","r",stdin);
    freopen("output.txt","w",stdout);
    #endif
    fio;
    vpii v;
    ll n;
    cin>>n;
    fr1(i,n){
        ll x,y;
        cin>>x>>y;
        v.pb({y,x});
    }
    sort(v.begin(),v.end(),ss);
    //fr1(i,n)cout<<v[i].fi<<" "<<v[i].se<<"\n";
    ll i=1;
    ll ans=0;
    ll cnt=v[0].fi;
    while(cnt>=i and cnt<=n){
        if(cnt+v[i].fi>=i)cnt+=v[i].fi;
        i++;
    }
    fr1(i,min(cnt+1,n))ans+=v[i].se;
    //cout<<cnt<<"\n";
    cout<<ans;
    return 0;
}


// Author:: MUKUL KUMAR RAI
// Institution:: Jalpaiguri Government Engineering College
//If you are not doing well now just stick to it and learn new things one day you will be...
//Compete with yourself
#include<bits/stdc++.h>
using namespace std;
#define ll long long int
#define ld long double
#define fi first
#define se second
#define pb push_back
///*template{{{
#define sz(x) (ll)x.size()
#define all(x) (x.begin(),x.end())
#define trav(a,x) for(auto &a:x)
#define fr(i,a,b)  for(ll i=a;i<=b;i++)
#define fr1(i,a)   for(ll i=0;i<a;i++)
#define frr(i,a,b) for(ll i=b;i>=a;i--)
#define frr1(i,a)   for(ll i=a-1;i>=0;i--)
#define sorta(a,n) sort(a,a+n)
#define sortd(a,n) sort(a,a+n,greater<ll>())
#define sortva(a) sort(a.begin(),a.end())
#define sortvd(a) sort(a.begin(),a.end(),greater<ll>())
#define tc(t) while(t--)
#define fio ios_base::sync_with_stdio(false);cin.tie(NULL);
using vi= vector<ll>;
using vvi= vector<vi>;
using vb =vector<bool>;
using vc =vector<char>;
using vs =vector<string>;
using vld =vector<ld>;
using pii =pair<ll,ll>;
using psi =pair<string,ll>;
using pci =pair<char,ll>;
using vpii =vector<pii>;
//}}}template*/
ll mod=1e9+7;
ll const maxn=1e5+5;
ll const inf=1e18;
bool ss(const pair<ll,ll> &a, const pair<ll,ll> &b) {
    if(a.first>b.first)
    return a.first>b.first;
    return a.second>b.second;
}
ll add(ll a,ll b){
    return ((a%mod)+(b%mod))%mod;
}
ll mul(ll a,ll b){
    return ((a%mod)*(b%mod))%mod;
}
ll powm(ll x,ll n,ll M)
{
    ll result=1;
    while(n>0)
    {
        if(n % 2 ==1)
            result=(result * x)%M;
        x=(x*x)%M;
        n=n/2;
    }
    return result;
}
ll modinverse(ll a, ll m){
    return powm(a,m-2,m);
}
bool prime(ll x){
    if(x<=1)return false;
    for(int i=2;i<=sqrt(x);i++)if(x%i==0)return false;
    return true;
}
ll divisor(ll x){
    ll cnt=0;
    for(int i=1;i<=sqrt(x);i++){
        if(x%i==0){
            if(i!=x/i)cnt+=2;
            else cnt+=1;
        }
    }
    return cnt;
}
vector<ll> sieve(ll n) {
    bool prim[n+1];
    memset(prim, true, sizeof(prim));

    for (ll p=2; p*p<=n; p++) {
        if (prim[p] == true) {
            for (int i=p*p; i<=n; i += p)
                prim[i] = false;
        }
    }
    vector<ll>v;
    for(int i=2;i<=n;i++)if(prim[i])v.push_back(i);
    return v;
}
int main(){
    #ifndef ONLINE_JUDGE
    freopen("input.txt","r",stdin);
    freopen("output.txt","w",stdout);
    #endif
    fio;
    vpii v;
    ll n;
    cin>>n;
    fr1(i,n){
        ll x,y;
        cin>>x>>y;
        v.pb({y,x});
    }
    sort(v.begin(),v.end(),ss);
    ll i=1;
    ll ans=0;
    ll cnt=v[0].fi+1;
    while(cnt>=(i+1) and cnt<n){
        cnt+=v[i].fi+1;
        i++;
    }
    //cout<<cnt<<"\n";
    fr1(i,min(cnt,n))ans+=v[i].se;
    cout<<ans;
    return 0;
}


// Author:: MUKUL KUMAR RAI
// Institution:: Jalpaiguri Government Engineering College
//If you are not doing well now just stick to it and learn new things one day you will be...
//Compete with yourself
#include<bits/stdc++.h>
using namespace std;
#define ll long long int
#define ld long double
#define fi first
#define se second
#define pb push_back
///*template{{{
#define sz(x) (ll)x.size()
#define all(x) (x.begin(),x.end())
#define trav(a,x) for(auto &a:x)
#define fr(i,a,b)  for(ll i=a;i<=b;i++)
#define fr1(i,a)   for(ll i=0;i<a;i++)
#define frr(i,a,b) for(ll i=b;i>=a;i--)
#define frr1(i,a)   for(ll i=a-1;i>=0;i--)
#define sorta(a,n) sort(a,a+n)
#define sortd(a,n) sort(a,a+n,greater<ll>())
#define sortva(a) sort(a.begin(),a.end())
#define sortvd(a) sort(a.begin(),a.end(),greater<ll>())
#define tc(t) while(t--)
#define fio ios_base::sync_with_stdio(false);cin.tie(NULL);
using vi= vector<ll>;
using vvi= vector<vi>;
using vb =vector<bool>;
using vc =vector<char>;
using vs =vector<string>;
using vld =vector<ld>;
using pii =pair<ll,ll>;
using psi =pair<string,ll>;
using pci =pair<char,ll>;
using vpii =vector<pii>;
//}}}template*/
ll mod=1e9+7;
ll const maxn=1e5+5;
ll const inf=1e18;
bool ss(const pair<ll,ll> &a, const pair<ll,ll> &b) {
    if(a.first>b.first)
    return a.first>b.first;
    return a.second>b.second;
}
ll add(ll a,ll b){
    return ((a%mod)+(b%mod))%mod;
}
ll mul(ll a,ll b){
    return ((a%mod)*(b%mod))%mod;
}
ll powm(ll x,ll n,ll M)
{
    ll result=1;
    while(n>0)
    {
        if(n % 2 ==1)
            result=(result * x)%M;
        x=(x*x)%M;
        n=n/2;
    }
    return result;
}
ll modinverse(ll a, ll m){
    return powm(a,m-2,m);
}
bool prime(ll x){
    if(x<=1)return false;
    for(int i=2;i<=sqrt(x);i++)if(x%i==0)return false;
    return true;
}
ll divisor(ll x){
    ll cnt=0;
    for(int i=1;i<=sqrt(x);i++){
        if(x%i==0){
            if(i!=x/i)cnt+=2;
            else cnt+=1;
        }
    }
    return cnt;
}
vector<ll> sieve(ll n) {
    bool prim[n+1];
    memset(prim, true, sizeof(prim));

    for (ll p=2; p*p<=n; p++) {
        if (prim[p] == true) {
            for (int i=p*p; i<=n; i += p)
                prim[i] = false;
        }
    }
    vector<ll>v;
    for(int i=2;i<=n;i++)if(prim[i])v.push_back(i);
    return v;
}
int main(){
    #ifndef ONLINE_JUDGE
    freopen("input.txt","r",stdin);
    freopen("output.txt","w",stdout);
    #endif
    fio;
    vpii v;
    ll n;
    cin>>n;
    fr1(i,n){
        ll x,y;
        cin>>x>>y;
        v.pb({y,x});
    }
    sort(v.begin(),v.end(),ss);
    //fr1(i,n)cout<<v[i].fi<<" "<<v[i].se<<"\n";
    ll i=1;
    ll ans=0;
    ll cnt=v[0].fi+1;
    while(cnt>=(i+1) and cnt<=n){
        cnt+=v[i].fi;
        if(v[i].fi>0)cnt++;
        i++;
    }
    //cout<<cnt<<"\n";
    fr1(i,min(cnt,n))ans+=v[i].se;
    cout<<ans;
    return 0;
}


/*
   By Anmol Gupta :)
*/
#include<bits/stdc++.h>
using namespace std;
#pragma GCC optimize("O3")
#define pb push_back
#define debug(x)  cout<<'>'<<#x<<" : "<<x<<endl;
#define mp make_pair
#define ff first
#define ss second
#define allunique(v) 	v.erase(unique(v.begin(),v.end()),v.end());
#define endl "\n"
#define MOD 1000000007
#define MOD9 1000000009
#define gc getchar_unlocked
#define ms(s, n) memset(s, n, sizeof(s))
#define prec(n) fixed<<setprecision(n)
#define eps 0.000001
#define pll pair<ll,ll>
#define all(v) v.begin(), v.end()
#define bolt ios::sync_with_stdio(0)
#define forr(i,n) for(ll i=0;i<n;i++)
#define eof (scanf("%d" ,&n))!=EOF
#define PI acos(-1.0)
typedef long long ll;
bool compare(pll x,pll y)
{
	if(x.second == y.second)
		return x.first > y.first;
	return x.second > y.second;
}
int main()
{
	ios_base::sync_with_stdio(false);
	cin.tie(NULL);
	cout.tie(NULL);
	//printf("%I64d", n)
	ll n,a,b,res;
	cin>>n;
	vector<pll> v;
	for(int i = 0;i<n;i++)
	{
		cin>>a>>b;
		v.pb(mp(a,b));
	}
	sort(all(v),compare);
	ll chances = 1;
	int i = 0;
	while(chances > 0 and i < n)
	{
		chances--;
		res += v[i].first;
		chances += v[i++].second;

	}
	cout<<res<<endl;
}


/*
   By Anmol Gupta :)
*/
#include<bits/stdc++.h>
using namespace std;
#pragma GCC optimize("O3")
#define pb push_back
#define debug(x)  cout<<'>'<<#x<<" : "<<x<<endl;
#define mp make_pair
#define ff first
#define ss second
#define allunique(v) 	v.erase(unique(v.begin(),v.end()),v.end());
#define endl "\n"
#define MOD 1000000007
#define MOD9 1000000009
#define gc getchar_unlocked
#define ms(s, n) memset(s, n, sizeof(s))
#define prec(n) fixed<<setprecision(n)
#define eps 0.000001
#define pll pair<ll,ll>
#define all(v) v.begin(), v.end()
#define bolt ios::sync_with_stdio(0)
#define forr(i,n) for(ll i=0;i<n;i++)
#define eof (scanf("%d" ,&n))!=EOF
#define PI acos(-1.0)
typedef long long ll;
bool compare(pll x,pll y)
{
	if(x.second == y.second){
		return x.first > y.first;
	}
	return x.second > y.second;
}
int main()
{
	ios_base::sync_with_stdio(false);
	cin.tie(NULL);
	cout.tie(NULL);
	//printf("%I64d", n)
	ll n,a,b,res;
	cin>>n;
	vector<pll> v;
	for(int i = 0;i<n;i++)
	{
		cin>>a>>b;
		v.pb(mp(a,b));
	}
	sort(all(v),compare);
	ll chances = 1;
	int i = 0;
	while(chances > 0 and i < n)
	{
		chances--;
		res += v[i].first;
		chances += v[i++].second;

	}
	cout<<res<<endl;
	return 0;
}


/*
   By Anmol Gupta :)
*/
#include<bits/stdc++.h>
using namespace std;
#pragma GCC optimize("O3")
#define pb push_back
#define debug(x)  cout<<'>'<<#x<<" : "<<x<<endl;
#define mp make_pair
#define ff first
#define ss second
#define allunique(v) 	v.erase(unique(v.begin(),v.end()),v.end());
#define endl "\n"
#define MOD 1000000007
#define MOD9 1000000009
#define gc getchar_unlocked
#define ms(s, n) memset(s, n, sizeof(s))
#define prec(n) fixed<<setprecision(n)
#define eps 0.000001
#define pii pair<ll,ll>
#define all(v) v.begin(), v.end()
#define bolt ios::sync_with_stdio(0)
#define forr(i,n) for(ll i=0;i<n;i++)
#define eof (scanf("%d" ,&n))!=EOF
#define PI acos(-1.0)
typedef long long ll;
#define MOD 1000000007
#define maxn 1001
#define ALP 26

int n;
pii a[maxn];

bool cmp(pii a, pii b)
{
	if (a.second > b.second) return 1;
	if (a.second == b.second && a.first > b.first) return 1;
	return 0;
}

int main()
{

	ios::sync_with_stdio(0);
	cin.tie(0);
	while (cin >> n)
	{
		for (int i = 0; i < n; ++i) cin >> a[i].first >> a[i].second;
		sort(a, a + n, cmp);
		int ans = 0;
		int can = 1;
		int p = 0;
		while (p<n && can>0)
		{
			pii v = a[p++];
			ans += v.first;
			can += v.second - 1;
		}
		cout << ans << endl;
	}
}


/*
   By Anmol Gupta :)
*/
#include<bits/stdc++.h>
using namespace std;
#pragma GCC optimize("O3")
#define pb push_back
#define debug(x)  cout<<'>'<<#x<<" : "<<x<<endl;
#define mp make_pair
#define ff first
#define ss second
#define allunique(v) 	v.erase(unique(v.begin(),v.end()),v.end());
#define endl "\n"
#define MOD 1000000007
#define MOD9 1000000009
#define gc getchar_unlocked
#define ms(s, n) memset(s, n, sizeof(s))
#define prec(n) fixed<<setprecision(n)
#define eps 0.000001
#define pll pair<ll,ll>
#define all(v) v.begin(), v.end()
#define bolt ios::sync_with_stdio(0)
#define forr(i,n) for(ll i=0;i<n;i++)
#define eof (scanf("%d" ,&n))!=EOF
#define PI acos(-1.0)
typedef long long ll;
bool compare(pll x,pll y)
{
	if(x.second == y.second)
		return x.first > y.first;
	return x.second > y.second;
}
int main()
{
	ios_base::sync_with_stdio(false);
	cin.tie(NULL);
	cout.tie(NULL);
	//printf("%I64d", n)
	ll n,a,b,res;
	cin>>n;
	vector<pll> v;
	for(int i = 0;i<n;i++)
	{
		cin>>a>>b;
		v.pb(mp(a,b));
	}
	sort(all(v),compare);
	// res = v[0].first;
	// for(auto i : v)
		// cout<<i.first<<" "<<i.second<<endl;
	ll chances = 1;
	// ll chances = v[0].second;
	int i = 0;
	while(chances > 0 and i < n)
	{
		chances--;
		res += v[i].first;
		chances += v[i++].second;

	}
	cout<<res<<endl;
}


#include<bits/stdc++.h>
using namespace std;
int main(){
	int N,a,b,score=0,cardsLeft=1;
	vector<int> v;
	cin>>N;
	for (int i=0;i<N;i++){
		cin>>a >>b;
		if (b!=0){
			score+=a;
			cardsLeft+=b-1;}
		else {v.push_back(a);}}
	sort(v.begin(),v.end(),greater<int>());
	for (int i=0;i<cardsLeft;i++){
		score+=v[i];}
	cout<<score;}


#include<bits/stdc++.h>
using namespace std;
int main(){
	long long N,a,b,score=0,cardsLeft=1;
	vector<int> v;
	cin>>N;
	for (int i=0;i<N;i++){
		cin>>a >>b;
		if (b!=0){
			score+=a;
			cardsLeft+=b-1;}
		else {v.push_back(a);}}
	if (v.size()!=0){
	sort(v.begin(),v.end(),greater<int>());
	for (int i=0;i<cardsLeft;i++){
		score+=v[i];}}
	cout<<score;}


#include<bits/stdc++.h>
using namespace std;
int main(){
	int N,a,b,score=0,cardsLeft=1;
	vector<int> v;
	cin>>N;
	for (int i=0;i<N;i++){
		cin>>a >>b;
		if (b!=0){
			score+=a;
			cardsLeft+=b-1;}
		else {v.push_back(a);}}
	if (v.size()!=0){
	sort(v.begin(),v.end(),greater<int>());
	for (int i=0;i<min(cardsLeft,signed(v.size()));i++){
		score+=v[i];}}
	cout<<score;}


#include<bits/stdc++.h>
using namespace std;
int main(){
	int N,a,b,score=0,cardsLeft=1;
	vector<int> v;
	cin>>N;
	for (int i=0;i<N;i++){
		cin>>a >>b;
		if (b!=0){
			score+=a;
			cardsLeft+=b-1;}
		else {v.push_back(a);}}
	if (v.size()!=0){
	sort(v.begin(),v.end(),greater<int>());
	for (int i=0;i<cardsLeft;i++){
		score+=v[i];}}
	cout<<score;}


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

int main() {

	int n, k, m;
	cin >> n >> k >> m;

	vector<string> v(n);
	vector<int > cost(n);

	for( int i = 0; i < n; i++){
		cin >> v[i];
	}

	for( int i = 0; i < n; i++){
		cin >> cost[i];
	}

//	vector<vector<int> > arr(k);
	map<string, int > mp;
	vector<int> g(k);
	for( int i = 0; i < k; i++ ){

		int x;
		cin >> x;
		int minval = INT_MAX;

		for( int j = 0; j < x; j++ ){

			int val;
			cin >> val;
			mp[v[val - 1]] = i;
			minval = min(minval, cost[val - 1]);

		}
		g[i] = minval;

	}

//	vector<string> code(m);
	string str;
	long long  ans = 0;

	for( int i  = 0; i < m; i++){

		cin >> str;
		ans += g[mp[str]];

	}

	cout << ans;

	return 0;
}


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

int main() {

	int n, k, m;
	cin >> n >> k >> m;

	vector<string> v(n);
	vector<long> cost(n);

	for( int i = 0; i < n; i++){
		cin >> v[i];
	}

	for( int i = 0; i < n; i++){
		cin >> cost[i];
	}

//	vector<vector<int> > arr(k);
	map<string, long> mp;

	for( int i = 0; i < k; i++ ){

		int x;
		cin >> x;
		long prev = 9999999999;

		for( int j = 0; j < x; j++ ){

			int val;
			cin >> val;
			mp[v[val - 1]] = min(cost[val - 1], prev);
			prev = cost[val - 1];

		}
	}

	vector<string> code(m);

	long long  ans = 0;

	for( int i  = 0; i < m; i++){

		cin >> code[i];
		ans += mp[code[i]];

	}

	cout << ans;

	return 0;
}


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

int main() {

	int n, k, m;
	cin >> n >> k >> m;

	vector<string> v(n);
	vector<long long > cost(n);

	for( int i = 0; i < n; i++){
		cin >> v[i];
	}

	for( int i = 0; i < n; i++){
		cin >> cost[i];
	}

//	vector<vector<int> > arr(k);
	map<string, long long > mp;

	for( int i = 0; i < k; i++ ){

		int x;
		cin >> x;
		long long  prev = 9999999999;

		for( int j = 0; j < x; j++ ){

			int val;
			cin >> val;
			mp[v[val - 1]] = min(cost[val - 1], prev);
			prev = mp[v[val - 1]];

		}
	}

//	vector<string> code(m);
	string str;
	long long  ans = 0;

	for( int i  = 0; i < m; i++){

		cin >> str;
		ans += mp[str];

	}

	cout << ans;

	return 0;
}


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

int main() {

	int n, k, m;
	cin >> n >> k >> m;

	vector<string> v(n);
	vector<long> cost(n);

	for( int i = 0; i < n; i++){
		cin >> v[i];
	}

	for( int i = 0; i < n; i++){
		cin >> cost[i];
	}

//	vector<vector<int> > arr(k);
	map<string, long> mp;

	for( int i = 0; i < k; i++ ){

		int x;
		cin >> x;
		long prev = 999999999;
		for( int j = 0; j < x; j++ ){
			int val;
			cin >> val;
			mp[v[val - 1]] = min(cost[val - 1], prev);
			prev = cost[val - 1];
			//arr[i][j] = cost[val];
		}
		//sort(v[i].begin(), v[i].end());

	}

	vector<string> code(m);
	long ans = 0;
	for( int i  = 0; i < m; i++){
		cin >> code[i];
		ans += mp[code[i]];
	}
	cout << ans;
	return 0;
}


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

int main() {

	int n, k, m;
	cin >> n >> k >> m;

	vector<string> v(n);
	vector<long long > cost(n);

	for( int i = 0; i < n; i++){
		cin >> v[i];
	}

	for( int i = 0; i < n; i++){
		cin >> cost[i];
	}

//	vector<vector<int> > arr(k);
	map<string, long long > mp;

	for( int i = 0; i < k; i++ ){

		int x;
		cin >> x;
		long long  prev = 999999999999;

		for( int j = 0; j < x; j++ ){

			int val;
			cin >> val;
			mp[v[val - 1]] = min(cost[val - 1], prev);
			prev = cost[val - 1];

		}
	}

	vector<string> code(m);

	long long  ans = 0;

	for( int i  = 0; i < m; i++){

		cin >> code[i];
		ans += mp[code[i]];

	}

	cout << ans;

	return 0;
}


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

vector <string> words;
long long cost[500000];
int group[500000];
long long mincost[500000];
int n,k,m;

int getStrInd(string in){
	for(int i = 0; i < n; i++){
		if(!words[i].compare(in)){
			return i;
		}
	}
}

int main(){
	scanf("%d",&n);
	scanf("%d",&k);
	scanf("%d",&m);
	words.reserve(500000);
	for(int i = 0; i < n; i++){
		string temp;
		cin >> temp;
		words.push_back(temp);
	}
	for(int i = 0; i < n; i++){
		long long temps;
		scanf("%I64d",&temps);
		cost[i] = temps;
	}
	for(int i = 0; i < k; i++){
		int num;
		scanf("%d",&num);
		int min = 2147483647;
		for(int j = 0; j < num; j++){
			int temps;
			scanf("%d",&temps);
			temps--;
			group[temps] = i;
			if(cost[temps] < min){
				min = cost[temps];
			}
		}
		mincost[i] = min;
	}
	long long total = 0;
	for(int i = 0; i < m; i++){
		string t;
		cin >> t;
		total += mincost[group[getStrInd(t)]];
	}
	cout << total << endl;
}


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

int main(){
	string words[100000];
	long long val[100000];
	map<string, long long> word_val;
	long long n, k, m;
	scanf("%I64d",&n);
	scanf("%I64d",&k);
	scanf("%I64d",&m);
	for(long long i = 0; i < n; i++){
		cin >> words[i];
	}
	for(long long i = 0; i < n; i++){
		scanf("%I64d",&val[i]);
		word_val[words[i]] = val[i];
	}
	for(long long i = 0; i < k; i++){
		long long temp;
		long long min = 2147483647;
		long long index[100000];
		scanf("%I64d", &temp);
		for(long long j = 0; j < temp; j++){
			scanf("%I64d",&index[j]);
			index[j]--;
			if(val[index[j]] < min){
				min = val[index[j]];
			}
		}
		for(long long j = 0; j < temp; j++){
			word_val[words[index[j]]] = min;
		}
	}
	long long total = 0;
	for(long long i = 0; i < m; i++){
		string tmp;
		cin >> tmp;
		total += word_val[tmp];
	}
	cout << total << endl;
}


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

vector <string> words;
vector <long long> cost;
int n,k,m;

int getStrInd(string in){
	for(int i = 0; i < n; i++){
		if(!words[i].compare(in)){
			return i;
		}
	}
}

int main(){
	scanf("%d",&n);
	scanf("%d",&k);
	scanf("%d",&m);
	words.reserve(500000);
	cost.reserve(500000);
	for(int i = 0; i < n; i++){
		string temp;
		cin >> temp;
		words.push_back(temp);
	}
	for(int i = 0; i < n; i++){
		long long temps;
		scanf("%I64d",&temps);
		cost.push_back(temps);
	}
	for(int i = 0; i < k; i++){
		int num;
		scanf("%d",&num);
		vector <int> mincost;;
		mincost.reserve(500000);
		int min = 2147483647;
		for(int i = 0; i < num; i++){
			int temps;
			scanf("%d",&temps);
			temps--;
			mincost.push_back(temps);
			if(cost[temps] < min){
				min = cost[temps];
			}
		}
		for(int i = 0; i < num; i++){
			cost[mincost[i]] = min;
		}
	}
	long long total = 0;
	for(int i = 0; i < m; i++){
		string t;
		cin >> t;
		total += cost[getStrInd(t)];
	}
	cout << total << endl;
}


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

vector <string> words;
vector <long long> cost;
int n,k,m;

int getStrInd(string in){
	for(int i = 0; i < n; i++){
		if(!words[i].compare(in)){
			return i;
		}
	}
}

int main(){
	scanf("%d",&n);
	scanf("%d",&k);
	scanf("%d",&m);
	for(int i = 0; i < n; i++){
		string temp;
		cin >> temp;
		words.push_back(temp);
	}
	for(int i = 0; i < n; i++){
		long long temps;
		cin >> temps;
		cost.push_back(temps);
	}
	for(int i = 0; i < k; i++){
		int num;
		scanf("%d",&num);
		vector <int> mincost;
		int min = 9999999;
		for(int i = 0; i < num; i++){
			int temps;
			scanf("%d",&temps);
			temps--;
			mincost.push_back(temps);
			if(cost[temps] < min){
				min = cost[temps];
			}
		}
		for(int i = 0; i < num; i++){
			cost[mincost[i]] = min;
		}
	}
	long long total = 0;
	for(int i = 0; i < m; i++){
		string t;
		cin >> t;
		total += cost[getStrInd(t)];
	}
	cout << total << endl;
}


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

vector <string> words;
vector <long long> cost;
int n,k,m;

int getStrInd(string in){
	for(int i = 0; i < n; i++){
		if(!words[i].compare(in)){
			return i;
		}
	}
}

int main(){
	scanf("%d",&n);
	scanf("%d",&k);
	scanf("%d",&m);
	for(int i = 0; i < n; i++){
		string temp;
		cin >> temp;
		words.push_back(temp);
	}
	for(int i = 0; i < n; i++){
		long long temps;
		scanf("%I64d",&temps);
		cost.push_back(temps);
	}
	for(int i = 0; i < k; i++){
		int num;
		scanf("%d",&num);
		vector <int> mincost;
		int min = 2147483647;
		for(int i = 0; i < num; i++){
			int temps;
			scanf("%d",&temps);
			temps--;
			mincost.push_back(temps);
			if(cost[temps] < min){
				min = cost[temps];
			}
		}
		for(int i = 0; i < num; i++){
			cost[mincost[i]] = min;
		}
	}
	long long total = 0;
	for(int i = 0; i < m; i++){
		string t;
		cin >> t;
		total += cost[getStrInd(t)];
	}
	cout << total << endl;
}


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

vector <string> words;
vector <long long> cost;
int n,k,m;

int getStrInd(string in){
	for(int i = 0; i < n; i++){
		if(!words[i].compare(in)){
			return i;
		}
	}
}

int main(){
	scanf("%d",&n);
	scanf("%d",&k);
	scanf("%d",&m);
	for(int i = 0; i < n; i++){
		string temp;
		cin >> temp;
		words.push_back(temp);
	}
	for(int i = 0; i < n; i++){
		long long temps;
		cin >> temps;
		cost.push_back(temps);
	}
	for(int i = 0; i < k; i++){
		int num;
		scanf("%d",&num);
		vector <int> mincost;
		int min = 2147483647;
		for(int i = 0; i < num; i++){
			int temps;
			scanf("%d",&temps);
			temps--;
			mincost.push_back(temps);
			if(cost[temps] < min){
				min = cost[temps];
			}
		}
		for(int i = 0; i < num; i++){
			cost[mincost[i]] = min;
		}
	}
	long long total = 0;
	for(int i = 0; i < m; i++){
		string t;
		cin >> t;
		total += cost[getStrInd(t)];
	}
	cout << total << endl;
}


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

vector <string> words;
vector <long long> cost;
int n,k,m;

int getStrInd(string in){
	for(int i = 0; i < n; i++){
		if(!words[i].compare(in)){
			return i;
		}
	}
}

int main(){
	scanf("%d",&n);
	scanf("%d",&k);
	scanf("%d",&m);
	for(int i = 0; i < n; i++){
		string temp;
		cin >> temp;
		words.push_back(temp);
	}
	for(int i = 0; i < n; i++){
		long long temps;
		scanf("%I64d",&temps);
		cost.push_back(temps);
	}
	for(int i = 0; i < k; i++){
		int num;
		scanf("%d",&num);
		vector <int> mincost;
		int min = 2147483647;
		for(int j = 0; j < num; j++){
			int temps;
			scanf("%d",&temps);
			temps--;
			mincost.push_back(temps);
			if(cost[temps] < min){
				min = cost[temps];
			}
		}
		for(int j = 0; j < num; j++){
			cost[mincost[j]] = min;
		}
	}
	long long total = 0;
	for(int i = 0; i < m; i++){
		string t;
		cin >> t;
		total += cost[getStrInd(t)];
	}
	cout << total << endl;
}


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

vector <string> words;
vector <long long> cost;
int n,k,m;

int getStrInd(string in){
	for(int i = 0; i < n; i++){
		if(!words[i].compare(in)){
			return i;
		}
	}
}

int main(){
	scanf("%d",&n);
	scanf("%d",&k);
	scanf("%d",&m);
	for(int i = 0; i < n; i++){
		string temp;
		cin >> temp;
		words.push_back(temp);
	}
	for(int i = 0; i < n; i++){
		long long temps;
		scanf("%I64d",&temps);
		cost.push_back(temps);
	}
	for(int i = 0; i < k; i++){
		int num;
		scanf("%d",&num);
		vector <int> mincost;
		int min = 9999999;
		for(int i = 0; i < num; i++){
			int temps;
			scanf("%d",&temps);
			temps--;
			mincost.push_back(temps);
			if(cost[temps] < min){
				min = cost[temps];
			}
		}
		for(int i = 0; i < num; i++){
			cost[mincost[i]] = min;
		}
	}
	long long total = 0;
	for(int i = 0; i < m; i++){
		string t;
		cin >> t;
		total += cost[getStrInd(t)];
	}
	cout << total << endl;
}


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

vector <string> words;
vector <long long> cost;
int n,k,m;

int getStrInd(string in){
	for(int i = 0; i < n; i++){
		if(!words[i].compare(in)){
			return i;
		}
	}
}

int main(){
	scanf("%d",&n);
	scanf("%d",&k);
	scanf("%d",&m);
	words.reserve(500000);
	cost.reserve(500000);
	for(int i = 0; i < n; i++){
		string temp;
		cin >> temp;
		words.push_back(temp);
	}
	for(int i = 0; i < n; i++){
		long long temps;
		scanf("%I64d",&temps);
		cost.push_back(temps);
	}
	int mincost[500000];
	for(int i = 0; i < k; i++){
		int num;
		scanf("%d",&num);
		int min = 2147483647;
		for(int i = 0; i < num; i++){
			int temps;
			scanf("%d",&temps);
			temps--;
			mincost[i] = temps;
			if(cost[temps] < min){
				min = cost[temps];
			}
		}
		for(int i = 0; i < num; i++){
			cost[mincost[i]] = min;
		}
	}
	long long total = 0;
	for(int i = 0; i < m; i++){
		string t;
		cin >> t;
		total += cost[getStrInd(t)];
	}
	cout << total << endl;
}


#include<stdio.h>
#include<string.h>
#include<algorithm>
using namespace std;
#define ll long long
#define Max	100020
#include<map>
#include<string>
int f[Max];
int n,tt,k;
int a[Max];
map<string,int >m;

void init()
{
	int i,j;
	for(i = 1;i<=n;i++)
	{
		f[i] = i;
	}
}

int find(int u)
{
	if(f[u] == u)
		return u;
	else
	{
		f[u] = find(f[u]);
		return f[u];
	}
}
int main()
{
	int i,j;
	while(~scanf("%d%d%d",&n,&tt,&k))
	{
		m.clear();
		char str[30];
		for(i = 1;i<=n;i++)
		{
			scanf("%s",str);
			m[str] = i;
		}
		for(i = 1;i<=n;i++)
			scanf("%d",&a[i]);

		init();
		for(i = 0;i<k;i++)
		{
			int x;
			scanf("%d",&x);
			int kk,pp;
			for(j = 0;j<x;j++)
			{
				if(j!=0) pp = kk;
				scanf("%d",&kk);

				if(j!=0)
				{
					int t1 = find(pp);
					int t2 = find(kk);
					//printf("t1==%d\n")
					if(t1!=t2)
					{
						//printf("0000\n");
						if(a[t1]<a[t2])
						{
							f[t2] = t1;
							//printf("t1==%d t2==%d\n",t1,t2);
						}

						else f[t1] = t2;
					}
				}
			}
		}
		int sum = 0;

		int t1 = find(5);

		for(i = 0;i<tt;i++)
		{
			scanf("%s",str);
			int t1 = find(m[str]);

			sum += a[t1];
		}
		printf("%d\n",sum);
	}
	return 0;
}


#include<stdio.h>
#include<string.h>
#include<algorithm>
using namespace std;
#define ll long long
#define Max	200020
#include<map>
#include<string>
int f[Max];
int n,tt,k;
int a[Max];
map<string,int >m;

void init()
{
	int i,j;
	for(i = 1;i<=n;i++)
	{
		f[i] = i;
	}
}

int find(int u)
{
	if(f[u] == u)
		return u;
	else
	{
		f[u] = find(f[u]);
		return f[u];
	}
}
int main()
{
	int i,j;
	while(~scanf("%d%d%d",&n,&tt,&k))
	{
		m.clear();
		char str[30];
		for(i = 1;i<=n;i++)
		{
			scanf("%s",str);
			m[str] = i;
		}
		for(i = 1;i<=n;i++)
			scanf("%d",&a[i]);

		init();
		for(i = 0;i<k;i++)
		{
			int x;
			scanf("%d",&x);
			int kk,pp;
			for(j = 0;j<x;j++)
			{
				if(j!=0) pp = kk;
				scanf("%d",&kk);

				if(j!=0)
				{
					int t1 = find(pp);
					int t2 = find(kk);

					if(t1!=t2)
					{

						if(a[t1]<a[t2])
						{
							f[t2] = t1;
						}

						else f[t1] = t2;
					}
				}
			}
		}
		long long  sum = 0;

		for(i = 0;i<tt;i++)
		{
			scanf("%s",str);
			int t1 = find(m[str]);

			sum += a[t1];
		}
		printf("%lld\n",sum);
	}
	return 0;
}


#include<stdio.h>
#include<string.h>
#include<algorithm>
using namespace std;
#define ll long long
#define Max	200020
#include<map>
#include<string>
long long f[Max];
long long n,tt,k;
ll a[Max];
map<string,long long >m;

void init()
{
	long long i,j;
	for(i = 1;i<=n;i++)
		f[i] = i;
}

long long find(long long u)
{
	if(f[u] == u)
		return u;
	else
	{
		f[u] = find(f[u]);
		return f[u];
	}
}
int main()
{
	long long i,j;
	while(~scanf("%lld%lld%lld",&n,&tt,&k))
	{
		m.clear();
		char str[30];
		for(i = 1;i<=n;i++)
		{
			scanf("%s",str);
			m[str] = i;
		}
		for(i = 1;i<=n;i++)
			scanf("%lld",&a[i]);

		init();
		for(i = 0;i<tt;i++)
		{
			long long x;
			scanf("%lld",&x);
			long long kk,pp;
			for(j = 0;j<x;j++)
			{
				if(j!=0) pp = kk;
				scanf("%lld",&kk);

				if(j!=0)
				{
					long long t1 = find(pp);
					long long t2 = find(kk);

					if(t1!=t2)
					{
						if(a[t1]<a[t2])
						{
							f[t2] = t1;
						}
						else f[t1] = t2;
					}
				}
			}
		}
		long long  sum = 0;

		for(i = 0;i<k;i++)
		{
			scanf("%s",str);
			long long t1 = find(m[str]);

			sum += a[t1];
		}
		printf("%lld\n",sum);
	}
	return 0;
}


#include<stdio.h>
#include<string.h>
#include<algorithm>
using namespace std;
#define ll long long
#define Max	100020
#include<map>
#include<string>
long long b[Max];
long long n,tt,k;
ll a[Max];
char str[Max][30];
map<string,long long >m;

int main()
{
	long long i,j;
	while(~scanf("%lld%lld%lld",&n,&tt,&k))
	{
		m.clear();

		for(i = 1;i<=n;i++)
			scanf("%s",str[i]);
		for(i = 1;i<=n;i++)
			scanf("%lld",&a[i]);

		for(i = 0;i<k;i++)
		{
			long long x;
			scanf("%lld",&x);
			long long Mi = 1000000000;
			for(j = 0;j<x;j++)
			{

				scanf("%lld",&b[j]);
				Mi = min(Mi,a[b[j]]);
			}
			for(j = 0;j<x;j++)
			{
				m[str[b[j]]] = Mi;
			}
		}

		char s[30];
		ll sum = 0;
		for(i = 0;i<tt;i++)
		{
			scanf("%s",s);
			sum += m[s];
		}
		printf("%lld\n",sum);
	}
	return 0;
}


#include<stdio.h>
#include<string.h>
#include<algorithm>
using namespace std;
#define ll long long
#define Max	200020
#include<map>
#include<string>
int f[Max];
int n,tt,k;
ll a[Max];
map<string,int >m;

void init()
{
	int i,j;
	for(i = 1;i<=n;i++)
	{
		f[i] = i;
	}
}

int find(int u)
{
	if(f[u] == u)
		return u;
	else
	{
		f[u] = find(f[u]);
		return f[u];
	}
}
int main()
{
	int i,j;
	while(~scanf("%d%d%d",&n,&tt,&k))
	{
		m.clear();
		char str[30];
		for(i = 1;i<=n;i++)
		{
			scanf("%s",str);
			m[str] = i;
		}
		for(i = 1;i<=n;i++)
			scanf("%lld",&a[i]);

		init();
		for(i = 0;i<k;i++)
		{
			int x;
			scanf("%d",&x);
			int kk,pp;
			for(j = 0;j<x;j++)
			{
				if(j!=0) pp = kk;
				scanf("%d",&kk);

				if(j!=0)
				{
					int t1 = find(pp);
					int t2 = find(kk);

					if(t1!=t2)
					{

						if(a[t1]<a[t2])
						{
							f[t2] = t1;
						}
						else f[t1] = t2;
					}
				}
			}
		}
		long long  sum = 0;

		for(i = 0;i<tt;i++)
		{
			scanf("%s",str);
			int t1 = find(m[str]);

			sum += a[t1];
		}
		printf("%lld\n",sum);
	}
	return 0;
}


#include<stdio.h>
#include<string.h>
#include<algorithm>
using namespace std;
#define ll long long
#define Max	200020
#include<map>
#include<string>
long long f[Max];
long long n,tt,k;
ll a[Max];
map<string,long long >m;

void init()
{
	long long i,j;
	for(i = 1;i<=n;i++)
		f[i] = i;
}

long long find(long long u)
{
	if(f[u] == u)
		return u;
	else
	{
		f[u] = find(f[u]);
		return f[u];
	}
}
int main()
{
	long long i,j;
	while(~scanf("%lld%lld%lld",&n,&tt,&k))
	{
		m.clear();
		char str[30];
		for(i = 1;i<=n;i++)
		{
			scanf("%s",str);
			m[str] = i;
		}
		for(i = 1;i<=n;i++)
			scanf("%lld",&a[i]);

		init();
		for(i = 0;i<k;i++)
		{
			long long x;
			scanf("%lld",&x);
			long long kk,pp;
			for(j = 0;j<x;j++)
			{
				if(j!=0) pp = kk;
				scanf("%lld",&kk);

				if(j!=0)
				{
					long long t1 = find(pp);
					long long t2 = find(kk);

					if(t1!=t2)
					{
						if(a[t1]<a[t2])
						{
							f[t2] = t1;
						}
						else f[t1] = t2;
					}
				}
			}
		}
		long long  sum = 0;

		for(i = 0;i<tt;i++)
		{
			scanf("%s",str);
			long long t1 = find(m[str]);

			sum += a[t1];
		}
		printf("%lld\n",sum);
	}
	return 0;
}


#include<stdio.h>
#include<string.h>
#include<algorithm>
using namespace std;
#define ll long long
const int Max = 1e5+10;
#include<map>
#include<string>
#define INF 0x3f3f3f3f3f3f
long long b[Max];
long long n,tt,k;
ll a[Max];

char str[Max][30];
map<string,long long >m;

int main()
{
	long long i,j;
	while(~scanf("%lld%lld%lld",&n,&tt,&k))
	{
		m.clear();

		for(i = 1;i<=n;i++)
			scanf("%s",str[i]);
		for(i = 1;i<=n;i++)
			scanf("%lld",&a[i]);

		for(i = 0;i<k;i++)
		{
			long long x;
			scanf("%lld",&x);
			long long Mi = INF;
			for(j = 0;j<x;j++)
			{

				scanf("%lld",&b[j]);
				Mi = min(Mi,a[b[j]]);
			}
			for(j = 0;j<x;j++)
			{
				m[str[b[j]]] = Mi;
			}
		}

		char s[30];
		ll sum = 0;
		for(i = 0;i<tt;i++)
		{
			scanf("%s",s);
			sum += m[s];
		}
		printf("%lld\n",sum);
	}
	return 0;
}


#include<stdio.h>
#include<string.h>
#include<algorithm>
using namespace std;
#define ll long long
const int Max = 1e5+10;
#include<map>
#include<string>
#define INF 0x3f3f3f3f3f3f
long long b[Max];
long long n,tt,k;
ll a[Max];

char str[Max][30];
map<string,long long >m;

int main()
{
	long long i,j;
	while(~scanf("%lld%lld%lld",&n,&tt,&k))
	{
		m.clear();

		for(i = 1;i<=n;i++)
			scanf("%s",str[i]);
		for(i = 1;i<=n;i++)
			scanf("%lld",&a[i]);

		for(i = 0;i<tt;i++)
		{
			long long x;
			scanf("%lld",&x);
			long long Mi = INF;
			for(j = 0;j<x;j++)
			{
				scanf("%lld",&b[j]);
				Mi = min(Mi,a[b[j]]);
			}
			for(j = 0;j<x;j++)
			{
				m[str[b[j]]] = Mi;
			}
		}

		char s[30];
		ll sum = 0;
		for(i = 0;i<k;i++)
		{
			scanf("%s",s);
			sum += m[s];
		}
		printf("%lld\n",sum);
	}
	return 0;
}


#include<iostream>
#include<cstdio>
#include<cmath>
#include<cstring>
#include<algorithm>
#include<map>
#include<string>
#include<set>
#include<stack>
#include<vector>
#include<queue>
#include<functional>
#include<fstream>
#include <iomanip>
using namespace std;
//struct node
//{
//	char s[25];
//	int n;
//	friend bool operator<(node a,node b)
//	{
//		return a.n < b.n;
//	}
//}a[100005],b[100005];
string ss[100005];
int temp[100005];
map<string, int>mp;
int main()
{
	int n, m, k;
	cin >> n >> m >> k;
	getchar();
	for (int i = 1; i <= n; i++)
	{
		cin >> ss[i];
	}
	for (int i = 1; i <= n; i++)
	{
		int p;
		scanf("%d", &p);
		mp[ss[i]] = p;
	}
	//for (int i = 1; i <= k; i++)
	//{
	//	int num;
	//	scanf("%d", &num);
	//	for (int j = 1; j <= num; j++)
	//	{
	//		if (j == 1)
	//			b[i] = a[j];
	//		else
	//			b[i] = min(b[i], a[j]);
	//	}
	//}
	for (int i = 1; i <= k; i++)
	{
		int num;
		scanf("%d", &num);
		int mini = 0x3f3f3f3f;
		for (int j = 1; j <= num; j++)
		{
			scanf("%d",&temp[j]);
			if (mp[ss[temp[j]]] < mini)
				mini = mp[ss[temp[j]]];
		}
		for (int j = 1; j <= num; j++)
		{
			mp[ss[temp[j]]] = mini;
		}
	}
	int ans = 0;
	for (int i = 1; i <= m; i++)
	{
		string s;
		cin >> s;
		ans += mp[s];
	}
	cout << ans << endl;;
	return 0;
}


#include<iostream>
#include<cstdio>
#include<cmath>
#include<cstring>
#include<algorithm>
#include<map>
#include<string>
#include<set>
#include<stack>
#include<vector>
#include<queue>
#include<functional>
#include<fstream>
#include <iomanip>
using namespace std;
typedef long long LL;
//struct node
//{
//	char s[25];
//	int n;
//	friend bool operator<(node a,node b)
//	{
//		return a.n < b.n;
//	}
//}a[100005],b[100005];
string ss[100005];
LL temp[100005];
map<string, LL>mp;
int main()
{
	int n, m, k;
	cin >> n >> m >> k;
	getchar();
	for (int i = 1; i <= n; i++)
	{
		cin >> ss[i];
	}
	for (int i = 1; i <= n; i++)
	{
		LL p;
		scanf("%I64d", &p);
		mp[ss[i]] = p;
	}
	//for (int i = 1; i <= k; i++)
	//{
	//	int num;
	//	scanf("%d", &num);
	//	for (int j = 1; j <= num; j++)
	//	{
	//		if (j == 1)
	//			b[i] = a[j];
	//		else
	//			b[i] = min(b[i], a[j]);
	//	}
	//}
	for (int i = 1; i <= k; i++)
	{
		int num;
		scanf("%d", &num);
		int mini = 0x7fffffff;
		for (int j = 1; j <= num; j++)
		{
			scanf("%d",&temp[j]);
			if (mp[ss[temp[j]]] < mini)
				mini = mp[ss[temp[j]]];
		}
		for (int j = 1; j <= num; j++)
		{
			mp[ss[temp[j]]] = mini;
		}
	}
	LL ans = 0;
	for (int i = 1; i <= m; i++)
	{
		string s;
		cin >> s;
		ans += mp[s];
	}
	cout << ans << endl;;
	return 0;
}


#include<iostream>
#include<cstdio>
#include<cmath>
#include<cstring>
#include<algorithm>
#include<map>
#include<string>
#include<set>
#include<stack>
#include<vector>
#include<queue>
#include<functional>
#include<fstream>
#include <iomanip>
using namespace std;
typedef long long LL;
string ss[100005];
LL temp[100005];
map<string, LL>mp;
int main()
{
	int n, m, k;
	cin >> n >> k >> m;
	getchar();
	for (int i = 1; i <= n; i++)
	{
		cin >> ss[i];
	}
	for (int i = 1; i <= n; i++)
	{
		LL p;
		scanf("%I64d", &p);
		mp[ss[i]] = p;
	}
	for (int i = 1; i <= k; i++)
	{
		int num;
		scanf("%d", &num);
		LL mini = 1e18;
		for (int j = 1; j <= num; j++)
		{
			scanf("%d",&temp[j]);
			if (mp[ss[temp[j]]] < mini)
				mini = mp[ss[temp[j]]];
		}
		for (int j = 1; j <= num; j++)
		{
			mp[ss[temp[j]]] = mini;
		}
	}
	LL ans = 0;
	for (int i = 1; i <= m; i++)
	{
		string s;
		cin >> s;
		ans += mp[s];
	}
	cout << ans << endl;;
	return 0;
}


#include<iostream>
#include<cstdio>
#include<cmath>
#include<cstring>
#include<algorithm>
#include<map>
#include<string>
#include<set>
#include<stack>
#include<vector>
#include<queue>
#include<functional>
#include<fstream>
#include <iomanip>
using namespace std;
typedef long long LL;
//struct node
//{
//	char s[25];
//	int n;
//	friend bool operator<(node a,node b)
//	{
//		return a.n < b.n;
//	}
//}a[100005],b[100005];
string ss[100005];
LL temp[100005];
map<string, LL>mp;
int main()
{
	int n, m, k;
	cin >> n >> m >> k;
	getchar();
	for (int i = 1; i <= n; i++)
	{
		cin >> ss[i];
	}
	for (int i = 1; i <= n; i++)
	{
		LL p;
		scanf("I64%d", &p);
		mp[ss[i]] = p;
	}
	//for (int i = 1; i <= k; i++)
	//{
	//	int num;
	//	scanf("%d", &num);
	//	for (int j = 1; j <= num; j++)
	//	{
	//		if (j == 1)
	//			b[i] = a[j];
	//		else
	//			b[i] = min(b[i], a[j]);
	//	}
	//}
	for (int i = 1; i <= k; i++)
	{
		int num;
		scanf("%d", &num);
		int mini = 0x7fffffff;
		for (int j = 1; j <= num; j++)
		{
			scanf("%d",&temp[j]);
			if (mp[ss[temp[j]]] < mini)
				mini = mp[ss[temp[j]]];
		}
		for (int j = 1; j <= num; j++)
		{
			mp[ss[temp[j]]] = mini;
		}
	}
	LL ans = 0;
	for (int i = 1; i <= m; i++)
	{
		string s;
		cin >> s;
		ans += mp[s];
	}
	cout << ans << endl;;
	return 0;
}