#include <bits/stdc++.h>
using namespace std;
int main() {
  int cards;
  cin >> cards;
  int zeroBCards[cards];
  int zeroBCount = 0;
  int bonusRound = 1;
  int score = 0;
  for (int i = 0; i < cards; i++) {
    int aVal, bVal;
    cin >> aVal >> bVal;
    if (bVal != 0) {
      bonusRound += bVal - 1;
      score += aVal;
    } else {
      zeroBCards[zeroBCount] = aVal;
      zeroBCount++;
    }
  }
  sort(zeroBCards, zeroBCards + zeroBCount);
  for (int i = 0; i < bonusRound; i++) {
    if (zeroBCount == 0) break;
    score += zeroBCards[zeroBCount - 1];
    zeroBCount--;
    if (zeroBCount < 0) break;
  }
  cout << score;
  return 0;
}
