#include <bits/stdc++.h>
using namespace std;
bool sortbysec(const pair<int, int> &a, const pair<int, int> &b) {
  return (a.second < b.second);
}
int main() {
  long long int n;
  cin >> n;
  long long int ans = 0;
  long long int sum = 1;
  vector<pair<long long int, long long int>> arr(n);
  for (int i = 0; i < n; i++) {
    long long int x, y;
    cin >> x >> y;
    arr[i] = {x, y};
  }
  sort(arr.begin(), arr.end(), sortbysec);
  for (int i = n - 1; i >= 0; i--) {
    if (arr[i].second != 0) {
      sum += arr[i].second;
      ans += arr[i].first;
      sum--;
      arr[i].first = 0;
    } else
      break;
  }
  sort(arr.begin(), arr.end());
  int i = 0;
  int k = n;
  while (sum-- && k--) {
    ans += arr[n - 1 - i].first;
    i++;
  }
  cout << ans;
  return 0;
}
