#include <bits/stdc++.h>
using namespace std;
struct Card {
  int a, b;
} c[1005];
int cmp(Card a, Card b) { return a.a > b.a; }
int main() {
  int n, ta, tb;
  while (scanf("%d", &n) != EOF) {
    int sum_b = 1, res = 0, pos = 0;
    for (int i = 0; i < n; i++) {
      scanf("%d%d", &ta, &tb);
      if (tb) {
        sum_b += tb;
        res += ta;
      } else {
        c[pos].a = ta;
        c[pos].b = tb;
        pos++;
      }
    }
    sum_b -= (n - pos);
    sort(c, c + pos, cmp);
    for (int i = 0; i < pos && i < sum_b; i++) res += c[i].a;
    printf("%d\n", res);
  }
  return 0;
}
