#include <bits/stdc++.h>
using namespace std;
int main() {
  int n;
  cin >> n;
  long long cnt = 0, cards = 1;
  int get = 0;
  vector<int> ab;
  for (int i = 0; i < n; i++) {
    int a, b;
    cin >> a >> b;
    if (b > 0) {
      cnt += a;
      get++;
      cards += b - 1;
    } else {
      ab.push_back(a);
    }
  }
  sort(ab.rbegin(), ab.rend());
  for (int i = 0; i < cards && i < ab.size(); i++) {
    cnt += ab[i];
  }
  cout << cnt << endl;
  return 0;
}
