#include <bits/stdc++.h>
using namespace std;
vector<pair<long long, pair<long long, long long> > > v, v1;
bool vis[100000];
int main() {
  long long total;
  cin >> total;
  for (long long i = 1; i <= total; i++) {
    long long l, r;
    cin >> l >> r;
    v.push_back(make_pair(r, make_pair(l, i)));
    v1.push_back(make_pair(l, make_pair(r, i)));
  }
  sort(v.rbegin(), v.rend());
  long long sum = 1;
  long long ans = 0;
  for (long long i = 0; i < v.size(); i++) {
    long long temp = v[i].first;
    if (!temp) break;
    sum += temp;
    sum--;
    ans += v[i].second.first;
    vis[v[i].second.second] = 1;
  }
  sort(v1.rbegin(), v1.rend());
  for (long long i = 0; i < v1.size(); i++) {
    if (!sum) break;
    if (vis[v1[i].second.second]) continue;
    sum--;
    ans += v1[i].first;
  }
  cout << ans << endl;
}
