#include <bits/stdc++.h>
long long int a[100000];
using namespace std;
int main() {
  long long int i, j, n, t, a, b, c = 1, p = 0, p1 = 0, p2;
  map<long long int, long long int> mp;
  map<long long int, long long int>::iterator it;
  vector<pair<long long int, long long int> > v, v1;
  vector<long long int> v3, v4;
  list<long long int> l;
  string s1;
  cin >> n;
  for (i = 0; i < n; i++) {
    cin >> a >> b;
    v3.push_back(a);
    v4.push_back(b);
  }
  for (i = 0; i < n; i++) v.push_back(make_pair(v3[i], v4[i]));
  sort(v.begin(), v.end());
  for (i = v.size() - 1; i >= 0; i--) {
    c--;
    p += v[i].first;
    c += v[i].second;
    if (c == 0) break;
  }
  for (i = 0; i < n; i++) v1.push_back(make_pair(v4[i], v3[i]));
  sort(v1.begin(), v1.end());
  c = 1;
  for (i = v1.size() - 1; i >= 0; i--) {
    c--;
    p1 += v1[i].second;
    c += v1[i].first;
    if (c == 0) break;
  }
  p2 = max(p, p1);
  cout << p2 << endl;
  v.clear();
  v1.clear();
  v3.clear();
  v4.clear();
  return 0;
}
