#include <bits/stdc++.h>
using namespace std;
signed main() {
  ios_base::sync_with_stdio(false);
  cin.tie(0);
  cout.tie(0);
  long long tests = 1;
  while (tests--) {
    long long n;
    cin >> n;
    long long cnt = 0, sum = 0, t = 0;
    vector<long long> v;
    for (long long i = 0; i < n; i++) {
      long long a, b;
      cin >> a >> b;
      if (b >= 1) {
        sum += a;
        cnt += b;
        t++;
      } else {
        v.push_back(a);
      }
    }
    sort(v.begin(), v.end());
    long long k = 1 + cnt - t;
    for (long long i = 0; i < min(k, (long long)v.size()); i++) {
      sum += v[(long long)v.size() - i - 1];
    }
    cout << sum;
  }
}
