#include <bits/stdc++.h>   using namespace std;   int main() {     ios_base::sync_with_stdio(false);     cin.tie(NULL);     long long a[1005], b[1005], n, i, j, k, temp, sum;     cin >> n;     for (i = 0; i < n; i++) {       cin >> a[i];       cin >> b[i];     }     for (i = 0; i < n - 1; i++) {       for (j = 0; j < n - i - 1; j++) {         if (b[j] > b[j + 1]) {           temp = b[j];           b[j] = b[j + 1];           b[j + 1] = temp;           temp = a[j];           a[j] = a[j + 1];           a[j + 1] = temp;         } else if (b[j] == b[j + 1]) {           if (a[j] > a[j + 1]) {             temp = a[j];             a[j] = a[j + 1];             a[j + 1] = temp;           }         }       }     }     sum = 0;     k = 1;     for (i = n - 1; i >= 0; i--) {       if (k > 0) {         sum += a[i];         k -= 1;       }       k += b[i];       if (k == 0) break;     }     cout << sum << endl;     return 0;   }   