import java.util.*;
import java.io.*;
import java.awt.Point;

public class p155B {
	public static void main(String[] args) {
		Scanner in = new Scanner(System.in);

		int n = in.nextInt();
		Point[] parr = new Point[n];
		for(int i=0; i<n; ++i) parr[i] = new Point(in.nextInt(), in.nextInt());

		Arrays.sort(parr, new Comparator<Point>(){
			public int compare(Point a, Point b) {
				if(a.y == b.y) return a.x-b.x;
				return a.y - b.y;
			}
		});

		int res = 0, count = 1;
		for(int i=n-1; i>=0 && count > 0; --i, --count) {
			res += parr[i].x;
			count += parr[i].y;
		}

		System.out.println(res);
	}
}


package level2;

import java.util.Scanner;

public class Cards {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub

		Scanner scan = new Scanner(System.in);
		int number = Integer.parseInt(scan.nextLine());

		int [] a = new int[number];
		int [] b = new int[number];

	      int countCards=1;
		for (int i = 0; i < number; i++) {
			String[] temp = scan.nextLine().split(" ");
			a[i] = Integer.parseInt(temp[0]);
			b[i] = Integer.parseInt(temp[1]);
			countCards+=b[i];

		}

		int i, j, maxIndex, tmp;
	      int n = b.length;
	      for (i = 0; i < n - 1; i++) {

	            maxIndex = i;
	            for (j = i + 1; j < n; j++)
	                  if (b[j] > b[maxIndex])
	                        maxIndex = j;
	            if (maxIndex != i) {

	                  tmp = b[i];
	                  b[i] = b[maxIndex];
	                  b[maxIndex] = tmp;

	                  tmp = a[i];
	                  a[i] = a[maxIndex];
	                  a[maxIndex] = tmp;

	            }
	      }
	      //System.out.println("C= "+countCards);
	      if(b[0]==0){
	    	  for (i = 0; i < n - 1; i++) {
		            maxIndex = i;
		            for (j = i + 1; j < n; j++)
		                  if (a[j] > a[maxIndex])
		                        maxIndex = j;
		            if (maxIndex != i) {

		                  tmp = b[i];
		                  b[i] = b[maxIndex];
		                  b[maxIndex] = tmp;

		                  tmp = a[i];
		                  a[i] = a[maxIndex];
		                  a[maxIndex] = tmp;

		            }
		      }
	      }
	      else if(countCards < number){

	    		for (i = 1; i < n - 1; i++) {
		            maxIndex = i;
		            for (j = i + 1; j < n; j++)
		                  if (a[j] > a[maxIndex])
		                        maxIndex = j;
		            if (maxIndex != i) {

		                  tmp = b[i];
		                  b[i] = b[maxIndex];
		                  b[maxIndex] = tmp;

		                  tmp = a[i];
		                  a[i] = a[maxIndex];
		                  a[maxIndex] = tmp;

		            }
		      }
			}

	    	int scores=0,numberOfCardsToPlay=1;

	    	for (int k = 0; k < b.length; k++) {
	    		//System.out.println(a[k]+" "+b[k]);
	    		if(!(numberOfCardsToPlay==0)){
				scores+=a[k];
				numberOfCardsToPlay--;
				numberOfCardsToPlay+=b[k];
	    		}
			}
		System.out.println(scores);

	}

}


import java.util.Scanner;

public class Main {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub

		Scanner scan = new Scanner(System.in);
		int number = Integer.parseInt(scan.nextLine());

		int [] a = new int[number];
		int [] b = new int[number];

	      int countCards=1;
		for (int i = 0; i < number; i++) {
			String[] temp = scan.nextLine().split(" ");
			a[i] = Integer.parseInt(temp[0]);
			b[i] = Integer.parseInt(temp[1]);
			countCards+=b[i];

		}

		int i, j, maxIndex, tmp;
		int maxtill=0;
	      int n = b.length;
	      for (i = 0; i < n - 1; i++) {

	            maxIndex = i;
	            for (j = i + 1; j < n; j++)
	                  if (b[j] > b[maxIndex])
	                        maxIndex = j;
	            if (maxIndex != i) {

	            		maxtill=i;
	                  tmp = b[i];
	                  b[i] = b[maxIndex];
	                  b[maxIndex] = tmp;

	                  tmp = a[i];
	                  a[i] = a[maxIndex];
	                  a[maxIndex] = tmp;

	            }
	      }
	     // System.out.println("C= "+countCards);
	      //System.out.println("MAX= "+maxtill);
	      if(b[0]==0){
	    	  for (i = 0; i < n - 1; i++) {
		            maxIndex = i;
		            for (j = i + 1; j < n; j++)
		                  if (a[j] > a[maxIndex])
		                        maxIndex = j;
		            if (maxIndex != i) {

		                  tmp = b[i];
		                  b[i] = b[maxIndex];
		                  b[maxIndex] = tmp;

		                  tmp = a[i];
		                  a[i] = a[maxIndex];
		                  a[maxIndex] = tmp;

		            }
		      }
	      }
	      else if(countCards < number){

	    		for (i = maxtill; i < n - 1; i++) {
		            maxIndex = i;
		            for (j = i + 1; j < n; j++)
		                  if (a[j] > a[maxIndex])
		                        maxIndex = j;
		            if (maxIndex != i) {

		                  tmp = b[i];
		                  b[i] = b[maxIndex];
		                  b[maxIndex] = tmp;

		                  tmp = a[i];
		                  a[i] = a[maxIndex];
		                  a[maxIndex] = tmp;

		            }
		      }
			}

	    	int scores=0,numberOfCardsToPlay=1;

	    	for (int k = 0; k < b.length; k++) {
	    		//System.out.println(a[k]+" "+b[k]);
	    		if(!(numberOfCardsToPlay==0)){
				scores+=a[k];
				numberOfCardsToPlay--;
				numberOfCardsToPlay+=b[k];
	    		}
			}
		System.out.println(scores);

	}

}


import java.util.Scanner;

public class Main {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub

		Scanner scan = new Scanner(System.in);
		int number = Integer.parseInt(scan.nextLine());

		int [] a = new int[number];
		int [] b = new int[number];

	      int countCards=1;
		for (int i = 0; i < number; i++) {
			String[] temp = scan.nextLine().split(" ");
			a[i] = Integer.parseInt(temp[0]);
			b[i] = Integer.parseInt(temp[1]);
			countCards+=b[i];

		}

		int i, j, maxIndex, tmp;
	      int n = b.length;
	      for (i = 0; i < n - 1; i++) {

	            maxIndex = i;
	            for (j = i + 1; j < n; j++)
	                  if (b[j] > b[maxIndex])
	                        maxIndex = j;
	            if (maxIndex != i) {

	                  tmp = b[i];
	                  b[i] = b[maxIndex];
	                  b[maxIndex] = tmp;

	                  tmp = a[i];
	                  a[i] = a[maxIndex];
	                  a[maxIndex] = tmp;

	            }
	      }
	      //System.out.println("C= "+countCards);
	      if(b[0]==0){
	    	  for (i = 0; i < n - 1; i++) {
		            maxIndex = i;
		            for (j = i + 1; j < n; j++)
		                  if (a[j] > a[maxIndex])
		                        maxIndex = j;
		            if (maxIndex != i) {

		                  tmp = b[i];
		                  b[i] = b[maxIndex];
		                  b[maxIndex] = tmp;

		                  tmp = a[i];
		                  a[i] = a[maxIndex];
		                  a[maxIndex] = tmp;

		            }
		      }
	      }
	      else if(countCards < number){

	    		for (i = 1; i < n - 1; i++) {
		            maxIndex = i;
		            for (j = i + 1; j < n; j++)
		                  if (a[j] > a[maxIndex])
		                        maxIndex = j;
		            if (maxIndex != i) {

		                  tmp = b[i];
		                  b[i] = b[maxIndex];
		                  b[maxIndex] = tmp;

		                  tmp = a[i];
		                  a[i] = a[maxIndex];
		                  a[maxIndex] = tmp;

		            }
		      }
			}

	    	int scores=0,numberOfCardsToPlay=1;

	    	for (int k = 0; k < b.length; k++) {
	    		//System.out.println(a[k]+" "+b[k]);
	    		if(!(numberOfCardsToPlay==0)){
				scores+=a[k];
				numberOfCardsToPlay--;
				numberOfCardsToPlay+=b[k];
	    		}
			}
		System.out.println(scores);

	}

}


import java.util.Scanner;

public class Main {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub

		Scanner scan = new Scanner(System.in);
		int number = Integer.parseInt(scan.nextLine());

		int [] a = new int[number];
		int [] b = new int[number];

	      int countCards=1;
		for (int i = 0; i < number; i++) {
			String[] temp = scan.nextLine().split(" ");
			a[i] = Integer.parseInt(temp[0]);
			b[i] = Integer.parseInt(temp[1]);
			countCards+=b[i];

		}

		int i, j, maxIndex, tmp;
		int maxtill=0;
	      int n = b.length;
	      for (i = 0; i < n - 1; i++) {

	            maxIndex = i;
	            for (j = i + 1; j < n; j++)
	                  if (b[j] > b[maxIndex])
	                        maxIndex = j;
	            if (maxIndex != i) {

	            		maxtill=i;
	                  tmp = b[i];
	                  b[i] = b[maxIndex];
	                  b[maxIndex] = tmp;

	                  tmp = a[i];
	                  a[i] = a[maxIndex];
	                  a[maxIndex] = tmp;

	            }
	      }
	      //System.out.println("C= "+countCards);
	      maxtill++;
	      //System.out.println("MAX= "+maxtill);

	      if(b[0]==0){
	    	  for (i = 0; i < n - 1; i++) {
		            maxIndex = i;
		            for (j = i + 1; j < n; j++)
		                  if (a[j] > a[maxIndex])
		                        maxIndex = j;
		            if (maxIndex != i) {

		                  tmp = b[i];
		                  b[i] = b[maxIndex];
		                  b[maxIndex] = tmp;

		                  tmp = a[i];
		                  a[i] = a[maxIndex];
		                  a[maxIndex] = tmp;

		            }
		      }
	      }
	      else if(countCards < number){

	    		for (i = maxtill; i < n - 1; i++) {
		            maxIndex = i;
		            for (j = i + 1; j < n; j++)
		                  if (a[j] > a[maxIndex])
		                        maxIndex = j;
		            if (maxIndex != i) {

		                  tmp = b[i];
		                  b[i] = b[maxIndex];
		                  b[maxIndex] = tmp;

		                  tmp = a[i];
		                  a[i] = a[maxIndex];
		                  a[maxIndex] = tmp;

		            }
		      }
			}

	    	int scores=0,numberOfCardsToPlay=1;

	    	for (int k = 0; k < b.length; k++) {
	    		//System.out.println(a[k]+" "+b[k]);
	    		if(!(numberOfCardsToPlay==0)){
				scores+=a[k];
				numberOfCardsToPlay--;
				numberOfCardsToPlay+=b[k];
	    		}
			}
		System.out.println(scores);

	}

}


import java.util.Scanner;

public class Main {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub

		Scanner scan = new Scanner(System.in);
		int number = Integer.parseInt(scan.nextLine());

		int [] a = new int[number];
		int [] b = new int[number];

		for (int i = 0; i < number; i++) {
			String[] temp = scan.nextLine().split(" ");
			a[i] = Integer.parseInt(temp[0]);
			b[i] = Integer.parseInt(temp[1]);

		}

		int i, j, maxIndex, tmp;
	      int n = b.length;
	      int countCards=0;
	      for (i = 0; i < n - 1; i++) {
	            maxIndex = i;
	            for (j = i + 1; j < n; j++)
	                  if (b[j] > b[maxIndex])
	                        maxIndex = j;
	            if (maxIndex != i) {

	                  tmp = b[i];
	                  b[i] = b[maxIndex];
	                  b[maxIndex] = tmp;

	                  tmp = a[i];
	                  a[i] = a[maxIndex];
	                  a[maxIndex] = tmp;

	            }
	      }
	      if(b[0]==0){
	    	  for (i = 0; i < n - 1; i++) {
		            maxIndex = i;
		            for (j = i + 1; j < n; j++)
		                  if (a[j] > a[maxIndex])
		                        maxIndex = j;
		            if (maxIndex != i) {

		                  tmp = b[i];
		                  b[i] = b[maxIndex];
		                  b[maxIndex] = tmp;

		                  tmp = a[i];
		                  a[i] = a[maxIndex];
		                  a[maxIndex] = tmp;

		            }
		      }
	      }else if(b[0]<number){

	    		for (i = 1; i < n - 1; i++) {
		            maxIndex = i;
		            for (j = i + 1; j < n; j++)
		                  if (a[j] > a[maxIndex])
		                        maxIndex = j;
		            if (maxIndex != i) {

		                  tmp = b[i];
		                  b[i] = b[maxIndex];
		                  b[maxIndex] = tmp;

		                  tmp = a[i];
		                  a[i] = a[maxIndex];
		                  a[maxIndex] = tmp;

		            }
		      }
			}

	    	int scores=0,numberOfCardsToPlay=1;

	    	for (int k = 0; k < b.length; k++) {
	    		if(!(numberOfCardsToPlay==0)){
				scores+=a[k];
				numberOfCardsToPlay--;
				numberOfCardsToPlay+=b[k];
	    		}
			}
		System.out.println(scores);

	}

}


import java.util.*;
import java.io.*;
public class carticas{
public static void main(String args[]) throws IOException{
BufferedReader lector = new BufferedReader(new InputStreamReader(System.in));
int tmp = Integer.parseInt(lector.readLine());
Vector<p> car = new Vector<p>();
for(int n =0;n<tmp;n++){
String t[] = lector.readLine().split(" ");
car.add(new p(Integer.parseInt(t[0]),Integer.parseInt(t[1]),0));
}
Collections.sort(car);
//System.out.println(car);
int r = 1,c=0,pun=0;
while(r>0 && c<car.size()){
p tal = car.get(c);
c++;
pun+=tal.a;
r+=tal.b;
r--;
}
System.out.println(pun);
}
}
class p implements Comparable{
int a,b,c;
public p(int a,int b,int c){
this.a = a;
this.b = b;
}
public int compareTo(Object o){
p pp =(p)o;
if(b==pp.b)return -1*(int)Math.signum(a-pp.a);
return  -1*(int)Math.signum(b-pp.b);
}
public String toString(){
return a+" "+b;
}
}


import java.util.PriorityQueue;
import java.util.Scanner;

public class Main {
	static class Card implements Comparable<Card>{
		int a, b;
		public Card(int x, int y){
			a = x;
			b = y;
		}
		@Override
		public int compareTo(Card o) {
			if(this.b != o.b)
				return o.b - this.b;
			return o.a - this.a;
		}
	}

	public static void main(String[] args)  {
		Scanner sc=  new Scanner(System.in);
		int n = sc.nextInt();
		PriorityQueue<Card> q = new PriorityQueue<Main.Card>();
		while(n-- != 0)
			q.add(new Card(sc.nextInt(), sc.nextInt()));

		int counter = 1;
		int points = 0;
		while(counter != 0){
			Card c = q.poll();
			points += c.a;
			counter--;
			counter += c.b;
		}

		System.out.println(points);
	}
}


import java.util.PriorityQueue;
import java.util.Scanner;

public class Main {
	static class Card implements Comparable<Card>{
		int a, b;
		public Card(int x, int y){
			a = x;
			b = y;
		}
		@Override
		public int compareTo(Card o) {
			if(this.b != o.b)
				return o.b - this.b;
			return o.a - this.a;
		}
	}

	public static void main(String[] args)  {
		Scanner sc=  new Scanner(System.in);
		int n = sc.nextInt();
		PriorityQueue<Card> q = new PriorityQueue<Main.Card>();
		while(n-- != 0)
			q.add(new Card(sc.nextInt(), sc.nextInt()));

		int counter = 1;
		int points = 0;
		while(counter != 0 && !q.isEmpty()){
			Card c = q.poll();
			points += c.a;
			counter--;
			counter += c.b;
		}

		System.out.println(points);
	}
}


import java.util.Arrays;
import java.util.Scanner;

public class B155 {

    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        int n = in.nextInt();
        Card[] cards = new Card[n];
        for (int i = 0; i < n; ++i) {
            cards[i] = new Card(in.nextInt(), in.nextInt());
        }
        int result = 0;
        int counter = 1;
        Arrays.sort(cards);
        for (int i = 0; i < n; ++i) {
            result += cards[i].top;
            counter += cards[i].bottom - 1;
            if (counter == 0) {
                break;
            }
        }
        System.out.println(result);
    }

    static class Card implements Comparable<Card> {
        public int top;
        public int bottom;

        public Card(int top, int bottom) {
            super();
            this.top = top;
            this.bottom = bottom;
        }

        @Override
        public int compareTo(Card c) {
            if (this.bottom != c.bottom) {
                return c.bottom - this.bottom;
            }
            return c.top - this.top;
        }
    }

}


import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.math.BigInteger;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.PriorityQueue;
import java.util.Scanner;
import java.util.Set;
import java.util.Stack;
import java.util.Vector;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Main {
	public static void main(String[] args) throws IOException {
		Task task = new Task();
		task.getData();
		task.solve();
		task.printAnswer();
	}
}

class Task {
	int[][] cards;

	StringBuilder answer = new StringBuilder();

	public void getData() throws IOException {
		BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

		cards = new int[Integer.parseInt(br.readLine())][2];

		for (int i = 0; i < cards.length; ++i) {
			String[] data = br.readLine().split(" ");
			cards[i][0] = Integer.parseInt(data[0]);
			cards[i][1] = Integer.parseInt(data[1]);
		}
	}

	public void solve() {
		Comparator<int[]> myComparator = new Comparator<int[]>() {
			@Override
			public int compare(int[] one, int[] two) {
				if (one[1] < two[1]) {
					return 1;
				}
				if (one[1] > two[1]) {
					return -11;
				}
				if (one[0] < two[0]) {
					return 1;
				}
				if (one[0] > two[0]) {
					return -1;
				}
				return 0;
			}
		};
		Arrays.sort(cards, myComparator);
		int totalScore = 0, points = 1;
		for (int[] current : cards) {
			totalScore += current[0];
			points = points - 1 + current[1];
			if (points == 0) {
				break;
			}
		}
		answer.append(totalScore);
	}

	public void printAnswer() {
		System.out.print(answer);
	}
}

class Team {
	int solved;
	int totalTime;

	Team(int solved, int totalTime) {
		this.solved = solved;
		this.totalTime = totalTime;
	}

	int compareTo(Team two) {
		if (solved == two.solved && totalTime == two.totalTime) {
			return 0;
		}
		if (solved > two.solved || solved == two.solved
				&& totalTime < two.totalTime) {
			return -1;
		}

		return 1;
	}

	@Override
	public boolean equals(Object o) {
		return (o instanceof Team) && compareTo((Team) o) == 0;
	}
}


import java.util.Arrays;
import java.util.Scanner;

public class comperato_saralash {
	static class Sort implements Comparable<Sort> {
		int x, y;

		Sort(int x, int y) {
			this.x = x;
			this.y = y;
		}

		public int compareTo(Sort arg0) {
			return -(this.x - arg0.x);
		}
	}

	public static void main(String[] args) {
		Scanner nm = new Scanner(System.in);
		int n = nm.nextInt();
		Sort[] a = new Sort[n + 1];
		int b[][] = new int[n + 1][n + 1];
		for (int i = 1; i <= n; i++) {
			b[i][1] = nm.nextInt();
			b[i][2] = nm.nextInt();
		}
		for (int i = 1; i <= n; i++) {
			a[i] = new Sort(b[i][1], b[i][2]);
		}
		Arrays.sort(a,1,n+1);
		for (int i = 1; i <= n; i++) {
			b[i][1] = a[i].x;
			b[i][2] = a[i].y;
		}
		for (int i = 1; i <= n; i++) {
			a[i] = new Sort(b[i][2], b[i][1]);
		}
		Arrays.sort(a,1,n+1);
		for (int i = 1; i <= n; i++) {
			b[i][1] = a[i].y;
			b[i][2] = a[i].x;
		}
		int inc=0,sum=0;
		for (int i = 1; i <= n; i++) {
			sum+=b[i][1];
			inc+=b[i][2]-1;
			if (inc==-1) {
				System.out.println(sum);
				return;
			}
		}
		System.out.println(sum);

	}
}


import java.util.Arrays;
import java.util.Scanner;

public class comperato_saralash {
	static class Sort implements Comparable<Sort> {
		int x, y;

		Sort(int x, int y) {
			this.x = x;
			this.y = y;
		}

		public int compareTo(Sort arg0) {
			return -(this.x - arg0.x);
		}
	}

	public static void main(String[] args) {
		Scanner nm = new Scanner(System.in);
		int n = nm.nextInt();
		Sort[] a = new Sort[n];
		int b[][] = new int[n][3];
		for (int i = 0; i < n; i++) {
			b[i][1] = nm.nextInt();
			b[i][2] = nm.nextInt();
		}
		for (int i = 0; i < n; i++) {
			a[i] = new Sort(b[i][1], b[i][2]);
		}
		Arrays.sort(a);
		for (int i = 0; i < n; i++) {
			b[i][1] = a[i].x;
			b[i][2] = a[i].y;
		}
		for (int i = 0; i < n; i++) {
			a[i] = new Sort(b[i][2], b[i][1]);
		}
		Arrays.sort(a);
		for (int i = 0; i < n; i++) {
			b[i][1] = a[i].y;
			b[i][2] = a[i].x;
		}
		long inc = 0, sum = 0;
		for (int i = 0; i < n; i++) {
			sum += (long) b[i][1];
			inc += (long) b[i][2] - 1;
			if (inc == -1) {
				System.out.println(sum);
				return;
			}
		}
		System.out.println(sum);

	}
}


import java.util.Arrays;
import java.util.Scanner;

public class comperato_saralash {
	static class Sort implements Comparable<Sort> {
		int x, y;

		Sort(int x, int y) {
			this.x = x;
			this.y = y;
		}

		public int compareTo(Sort arg0) {
			return -(this.x - arg0.x);
		}
	}

	public static void main(String[] args) {
		Scanner nm = new Scanner(System.in);
		int n = nm.nextInt();
		Sort[] a = new Sort[n + 1];
		int b[][] = new int[n + 1][n + 1];
		for (int i = 1; i <= n; i++) {
			b[i][1] = nm.nextInt();
			b[i][2] = nm.nextInt();
		}
		for (int i = 1; i <= n; i++) {
			a[i] = new Sort(b[i][1], b[i][2]);
		}
		Arrays.sort(a,1,n+1);
		for (int i = 1; i <= n; i++) {
			b[i][1] = a[i].x;
			b[i][2] = a[i].y;
		}
		for (int i = 1; i <= n; i++) {
			a[i] = new Sort(b[i][2], b[i][1]);
		}
		Arrays.sort(a,1,n+1);
		for (int i = 1; i <= n; i++) {
			b[i][1] = a[i].y;
			b[i][2] = a[i].x;
		}
		long inc=0,sum=0;
		for (int i = 1; i <= n; i++) {
			sum+=(long)b[i][1];
			inc+=(long)b[i][2]-1;
			if (inc==-1) {
				System.out.println(sum);
				return;
			}
		}
		System.out.println(sum);

	}
}


import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.StringTokenizer;

public class Combinations {
static	int a[];
	static int b[];
public static void main(String[]args) throws IOException{
	BufferedReader br =new BufferedReader(new InputStreamReader(System.in));
	int n =Integer.parseInt(br.readLine());
	a=new int[n];
	b=new int [n];
	StringTokenizer str;
	for (int i = 0; i < n; i++) {
		 str=new StringTokenizer(br.readLine());
		a[i]=Integer.parseInt(str.nextToken());
		b[i]=Integer.parseInt(str.nextToken());
		//System.out.println("4");

	}

	/*for (int i = 0; i < b.length; i++) {
		if (b[i]>max) {
			max=b[i];
			index=i;
		}else
			if (b[i]==max) {
				if (a[i]>a[index]) {
					i=index;
				}
			}
		b[index]=0;
		n--;
	}*/
	int sum=1;
	int sum1=0;

	while (n--!=0 && sum!=0) {
		//System.out.println("3");
int x =max(b);
//System.out.println(x);
sum+=b[x]-1;
b[x]=-1;
sum1+=a[x];
a[x]=-1;
	}

	System.out.println(sum1);

	/*for (int i = 0; i < b.length; i++) {

	}*/

//aa
}
public static int max(int[] x){

	int max=0;
	int index = 0;
	for (int i = 0; i < x.length; i++) {
		if (x[i]>max) {
			max=x[i];
			index=i;
		}else
			if (x[i]==max) {
				if (a[i]>=a[index]) {
					index=i;
				}
			}

	}

	return index;

}
}


import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.StringTokenizer;

public class Combinations {
static	int a[];
	static int b[];
public static void main(String[]args) throws IOException{
	BufferedReader br =new BufferedReader(new InputStreamReader(System.in));
	int n =Integer.parseInt(br.readLine());
	a=new int[n];
	b=new int [n];
	StringTokenizer str;
	for (int i = 0; i < n; i++) {
		 str=new StringTokenizer(br.readLine());
		a[i]=Integer.parseInt(str.nextToken());
		b[i]=Integer.parseInt(str.nextToken());
		//System.out.println("4");

	}

	/*for (int i = 0; i < b.length; i++) {
		if (b[i]>max) {
			max=b[i];
			index=i;
		}else
			if (b[i]==max) {
				if (a[i]>a[index]) {
					i=index;
				}
			}
		b[index]=0;
		n--;
	}*/
	int sum=1;
	int sum1=0;

	while (n--!=0 && sum!=0) {
		//System.out.println("3");
int x =max(b);
//System.out.println(x);
sum+=b[x]-1;
b[x]=-1;
sum1+=a[x];
a[x]=-1;
	}

	System.out.println(sum1);

	/*for (int i = 0; i < b.length; i++) {

	}*/

}
public static int max(int[] x){

	int max=0;
	int index = 0;
	for (int i = 0; i < x.length; i++) {
		if (x[i]>max) {
			max=x[i];
			index=i;
		}else
			if (x[i]==max) {
				if (a[i]>=a[index]) {
					index=i;
				}
			}

	}

	return index;

}
}


import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.StringTokenizer;

public class Combinations {
static	int a[];
	static int b[];
public static void main(String[]args) throws IOException{
	BufferedReader br =new BufferedReader(new InputStreamReader(System.in));
	int n =Integer.parseInt(br.readLine());
	a=new int[n];
	b=new int [n];
	StringTokenizer str;
	for (int i = 0; i < n; i++) {
		 str=new StringTokenizer(br.readLine());
		a[i]=Integer.parseInt(str.nextToken());
		b[i]=Integer.parseInt(str.nextToken());
		//System.out.println("4");

	}

	/*for (int i = 0; i < b.length; i++) {
		if (b[i]>max) {
			max=b[i];
			index=i;
		}else
			if (b[i]==max) {
				if (a[i]>a[index]) {
					i=index;
				}
			}
		b[index]=0;
		n--;
	}*/
	int sum=1;
	int sum1=0;

	while (n--!=0 && sum!=0) {
		//System.out.println("3");
int x =max(b);
//System.out.println(x);
sum+=b[x]-1;
b[x]=-1;
sum1+=a[x];
	}

	System.out.println(sum1);

	/*for (int i = 0; i < b.length; i++) {

	}*/

}
public static int max(int[] x){

	int max=0;
	int index = 0;
	for (int i = 0; i < x.length; i++) {
		if (x[i]>max) {
			max=x[i];
			index=i;
		}else
			if (x[i]==max) {
				if (a[i]>=a[index]) {
					index=i;
				}
			}

	}

	return index;

}
}


import java.util.*;

public class Combination {
    public static void main(String[] args) {
        Scanner cin = new Scanner(System.in);
        int n = cin.nextInt();
        int[][] t = new int[n][2];
        for (int i = 0; i < n; i++) {
            t[i][0] = cin.nextInt();
            t[i][1] = cin.nextInt();
        }
        Arrays.sort(t, new Comparator<int[]>() {
            public int compare(int[] a, int[] b) {
                if (a[1] > b[1]) {
                    return -1;
                }
                if (a[1] < b[1]) {
                    return 1;
                }
                if (a[0] > b[0]) {
                    return -1;
                }
                if (a[0] < b[0]) {
                    return 1;
                }
                return 0;
            }
        });
        int moves = 1;
        long sum = 0;
        int i = 0;
        while (moves > 0 && i < n) {
            moves += t[i][1];
            sum += t[i][0];
            moves--;
            i++;
        }
        System.out.println(sum);
    }
}


import java.io.*;
import java.util.*;

public class Main
{
	public static void main(String asr[])throws IOException
	{
		BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
		int n=Integer.parseInt(br.readLine());
		int ar[][]=new int[n][2];
		for(int i=0;i<n;i++)
		{
			String inp[]=(br.readLine()).split(" ");
			int a=Integer.parseInt(inp[0]);
			int b=Integer.parseInt(inp[1]);
			ar[i][0]=a;
			ar[i][1]=b;
		}
		int counter=1;
		int sum=0;
		boolean vis[]=new boolean[n];
		for(int i=0;i<n;i++)
			vis[i]=false;
		while(counter!=0)
		{
			if(allvis(vis))
				break;
			int indcc=nextcard(ar,vis);
			vis[indcc]=true;
			counter--;
			sum+=ar[indcc][0];
			counter+=ar[indcc][1];
		}
		System.out.println(sum);
	}
	public static int nextcard(int ar[][],boolean v[])
	{
		int maxv=-1;
		int ind=-1;
		int maxp=-1;
		for(int i=0;i<ar.length;i++)
		{
			if(v[i])
				continue;
			if(ar[i][1]>maxv)
			{
				maxv=ar[i][1];
				maxp=ar[i][0];
				ind=i;
			}
			else if(ar[i][1]==maxv)
			{
				if(maxp<ar[i][0])
				{
					maxv=ar[i][1];
					maxp=ar[i][0];
					ind=i;
				}
			}
		}
		return ind;
	}
	public static boolean allvis(boolean ar[])
	{
		for(int i=0;i<ar.length;i++)
		{
			if(!ar[i])
				return false;
		}
		return true;
	}
}


/**
 * Created by DELL on 05-Mar-16.
 */

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.StringTokenizer;
import java.util.TreeSet;

public class Main
{
    FastScanner in;
    PrintWriter out;

    public void solve() throws IOException
    {
        TreeSet<Card> cards = new TreeSet<Card>();
        int n = in.nextInt();
        for (int i = 0; i < n; i++)
        {
            cards.add(new Card(in.nextInt(), in.nextInt()));
        }
        int sum = 0;
        int left = 1;
        while (!cards.isEmpty() && left-- > 0)
        {
            Card temp = cards.pollFirst();
            sum += temp.point;
            left += temp.draw;
        }
        System.out.println(sum);
    }

    public void run()
    {
        try
        {
            in = new FastScanner();
            out = new PrintWriter(System.out);

            solve();

            out.close();
        } catch (IOException e)
        {
            e.printStackTrace();
        }
    }

    class FastScanner
    {
        BufferedReader br;
        StringTokenizer st;

        FastScanner()
        {
            br = new BufferedReader(new InputStreamReader(System.in));
        }

        String next()
        {
            while (st == null || !st.hasMoreTokens())
            {
                try
                {
                    st = new StringTokenizer(br.readLine());
                } catch (IOException e)
                {
                    e.printStackTrace();
                }
            }
            return st.nextToken();
        }

        int nextInt()
        {
            return Integer.parseInt(next());
        }
    }

    public static void main(String[] arg)
    {
        new Main().run();
    }
}

class Card implements Comparable<Card>
{
    int point;
    int draw;

    public Card(int point, int draw)
    {
        this.point = point;
        this.draw = draw;
    }

    public int compareTo(Card that)
    {
        int drawDiff = that.draw - this.draw;
        return drawDiff < 0 ? -1 : drawDiff > 0 ? +1 : that.point - this.point;
    }

}


/**
 * Created by DELL on 05-Mar-16.
 */

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.StringTokenizer;
import java.util.TreeSet;

public class Main
{
    FastScanner in;
    PrintWriter out;

    public void solve() throws IOException
    {
        TreeSet<Card> cards = new TreeSet<Card>();
        int n = in.nextInt();
        for (int i = 0; i < n; i++)
        {
            cards.add(new Card(in.nextInt(), in.nextInt()));
        }
        int sum = 0;
        int left = 1;
        /*while (!cards.isEmpty())
        {
            Card temp = cards.pollFirst();
            System.out.println("Points = " + temp.point + " Draw = " + temp.draw);
        }*/
        while (!cards.isEmpty() && left-- > 0)
        {
            Card temp = cards.pollFirst();
            sum += temp.point;
            left += temp.draw;
        }
        System.out.println(sum);
    }

    public void run()
    {
        try
        {
            in = new FastScanner();
            out = new PrintWriter(System.out);

            solve();

            out.close();
        } catch (IOException e)
        {
            e.printStackTrace();
        }
    }

    class FastScanner
    {
        BufferedReader br;
        StringTokenizer st;

        FastScanner()
        {
            br = new BufferedReader(new InputStreamReader(System.in));
        }

        String next()
        {
            while (st == null || !st.hasMoreTokens())
            {
                try
                {
                    st = new StringTokenizer(br.readLine());
                } catch (IOException e)
                {
                    e.printStackTrace();
                }
            }
            return st.nextToken();
        }

        int nextInt()
        {
            return Integer.parseInt(next());
        }
    }

    public static void main(String[] arg)
    {
        new Main().run();
    }
}

class Card implements Comparable<Card>
{
    int point;
    int draw;

    public Card(int point, int draw)
    {
        this.point = point;
        this.draw = draw;
    }

    public int compareTo(Card that)
    {
        int drawDiff = that.draw - this.draw;
        return drawDiff < 0 ? -1 : drawDiff > 0 ? +1 : that.point - this.point < 0 ? -1 : +1;
    }

}


import java.io.*;
import java.util.*;

public class Combination {
    public static void main(String[] args) throws IOException {
        BufferedReader f = new BufferedReader(new InputStreamReader(System.in));
        int n = Integer.parseInt(f.readLine());
        ComboCard[] a = new ComboCard[n];
        for (int i = 0; i < n; i++)
        {
            StringTokenizer st = new StringTokenizer(f.readLine());
            a[i] = new ComboCard(Integer.parseInt(st.nextToken()),Integer.parseInt(st.nextToken()));
        }
        Arrays.sort(a);
        int index = n-1;
        int count = 1;
        int sum = 0;
        while (index >= 0 && count > 0)
        {
            sum += a[index].a;
            count += a[index].b - 1;
            index--;
        }
        System.out.println(sum);
    }
}

class ComboCard implements Comparable<ComboCard>
{
    int a;
    int b;

    public ComboCard(int a, int b)
    {
        this.a = a;
        this.b = b;
    }

    public int compareTo(ComboCard c) {
        if (b != c.b)
            return b-c.b;
        return a-c.a;
    }
}


import java.util.*;
import java.io.*;

public class Main
{

            public static void main(String[] args)
            {

                    FastInput input = new FastInput(System.in);
                    PrintWriter output = new PrintWriter(System.out,true);

                    int n = input.readInt();
                    int steps=0,points =0,count=0;

                    Card[] array = new Card[n];

                    for(int i=0;i<n;++i)
                        array[i]= new Card(input.readInt() , input.readInt());

                    Arrays.sort(array);

                    for(int i=0;i<n;++i)
                    {
                            if(array[i].count>0)
                            {
                                    points+=array[i].point;
                                    steps += array[i].count;
                                    ++count;
                            }

                    }

                    if(steps==0)
                        steps=1;
                    else
                        steps = steps - (count-1);

                    for(int i=0;i<n;++i)
                    {
                            if(steps>0 && array[i].count==0)
                            {
                                points +=array[i].point;
                                --steps;
                            }

                    }

                    output.println(points);

                    input.close();
                    output.close();

            }
}

class Card implements Comparable<Card>
{
        int count;
        int point;

        Card(int point , int count)
        {
                this.count = count;
                this.point = point;

        }

        public int compareTo(Card x)
        {

                if(this.point > x.point)
                    return -1;
                else if(this.point == x.point)
                    return 0;
                else
                    return 1;

        }

}

class FastInput
{

        private InputStream stream;
        private byte[] buf = new byte[1024];
        private int curChar;
        private int numChars;

        public FastInput(InputStream userInputStream)
        {
            this.stream = userInputStream;

        }

        public int readChar()
        {

            if (numChars == -1)
                throw new InputMismatchException();

            if (curChar >= numChars)
            {

                curChar = 0;

                try
                {
                    numChars = stream.read(buf);
                }
                catch (IOException e)
                {
                    throw new InputMismatchException();
                }

                if (numChars <= 0)
                    return -1;

            }

            return buf[curChar++];

        }

        public boolean isSpaceChar(int c)
        {

                return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;

        }

        public int readInt()
        {

            int c = readChar();
            int sgn = 1;

            while (isSpaceChar(c))
                c = readChar();

            if (c == '-' )
            {
                sgn = -1;
                c = readChar();

            }

            int res = 0;

            do {

                if (c < '0' || c > '9')
                    throw new InputMismatchException();

                res *= 10;
                res += c - '0';
                c = readChar();

            } while (!isSpaceChar(c));

            return res * sgn;

        }

        public long readLong()
        {

            int c = readChar();
            int sgn = 1;

            while (isSpaceChar(c))
                c = readChar();

            if (c == '-' )
            {
                sgn = -1;
                c = readChar();

            }

            long res = 0;

            do {

                if (c < '0' || c > '9')
                    throw new InputMismatchException();

                res *= 10;
                res += c - '0';
                c = readChar();

            } while (!isSpaceChar(c));

            return res * sgn;

        }

        public String readString() {

            int c = readChar();

            while (isSpaceChar(c))
                c = readChar();

            StringBuilder res = new StringBuilder();

            do
            {

                res.append((char)c);
                c = readChar();

            } while (!isSpaceChar(c));

            return res.toString();

        }

        // The method created intially skips all whitespaces as defined above and then starts reading everything before \r , \n  , or both
        public String readLine()
        {
                int c=  readChar();

                while (isSpaceChar(c))
                    c = readChar();

                StringBuilder res = new StringBuilder();

                do
                {
                    res.append(c);
                    c = readChar();

                }while (c != '\r' &&  c!= '\n');

                return res.toString();

        }

        public void close()
        {
                try
                {
                    stream.close();
                }
                catch(IOException ex)
                {
                    ex.printStackTrace();

                }
        }

}


import java.util.*;
import java.io.*;

public class Main
{

            public static void main(String[] args)
            {

                    FastInput input = new FastInput(System.in);
                    PrintWriter output = new PrintWriter(System.out,true);

                    int n = input.readInt();
                    int steps=0 ,points =0;

                    Card[] array = new Card[n];

                    for(int i=0;i<n;++i)
                        array[i]= new Card(input.readInt() , input.readInt());

                    Arrays.sort(array);

                    for(int i=0;i<n;++i)
                    {
                            if(array[i].count>0)
                            {
                                    points+=array[i].point;
                                    steps += array[i].count;

                            }

                    }

                    for(int i=0;i<n;++i)
                    {
                            if(steps>0 && array[i].count==0)
                            {
                                points +=array[i].point;
                                --steps;
                            }

                    }

                    output.println(points);

                    input.close();
                    output.close();

            }
}

class Card implements Comparable<Card>
{
        int count;
        int point;

        Card(int point , int count)
        {
                this.count = count;
                this.point = point;

        }

        public int compareTo(Card x)
        {

                if(this.point > x.point)
                    return -1;
                else if(this.point == x.point)
                    return 0;
                else
                    return 1;

        }

}

class FastInput
{

        private InputStream stream;
        private byte[] buf = new byte[1024];
        private int curChar;
        private int numChars;

        public FastInput(InputStream userInputStream)
        {
            this.stream = userInputStream;

        }

        public int readChar()
        {

            if (numChars == -1)
                throw new InputMismatchException();

            if (curChar >= numChars)
            {

                curChar = 0;

                try
                {
                    numChars = stream.read(buf);
                }
                catch (IOException e)
                {
                    throw new InputMismatchException();
                }

                if (numChars <= 0)
                    return -1;

            }

            return buf[curChar++];

        }

        public boolean isSpaceChar(int c)
        {

                return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;

        }

        public int readInt()
        {

            int c = readChar();
            int sgn = 1;

            while (isSpaceChar(c))
                c = readChar();

            if (c == '-' )
            {
                sgn = -1;
                c = readChar();

            }

            int res = 0;

            do {

                if (c < '0' || c > '9')
                    throw new InputMismatchException();

                res *= 10;
                res += c - '0';
                c = readChar();

            } while (!isSpaceChar(c));

            return res * sgn;

        }

        public long readLong()
        {

            int c = readChar();
            int sgn = 1;

            while (isSpaceChar(c))
                c = readChar();

            if (c == '-' )
            {
                sgn = -1;
                c = readChar();

            }

            long res = 0;

            do {

                if (c < '0' || c > '9')
                    throw new InputMismatchException();

                res *= 10;
                res += c - '0';
                c = readChar();

            } while (!isSpaceChar(c));

            return res * sgn;

        }

        public String readString() {

            int c = readChar();

            while (isSpaceChar(c))
                c = readChar();

            StringBuilder res = new StringBuilder();

            do
            {

                res.append((char)c);
                c = readChar();

            } while (!isSpaceChar(c));

            return res.toString();

        }

        // The method created intially skips all whitespaces as defined above and then starts reading everything before \r , \n  , or both
        public String readLine()
        {
                int c=  readChar();

                while (isSpaceChar(c))
                    c = readChar();

                StringBuilder res = new StringBuilder();

                do
                {
                    res.append(c);
                    c = readChar();

                }while (c != '\r' &&  c!= '\n');

                return res.toString();

        }

        public void close()
        {
                try
                {
                    stream.close();
                }
                catch(IOException ex)
                {
                    ex.printStackTrace();

                }
        }

}


import java.util.*;
import java.io.*;

public class Main
{

            public static void main(String[] args)
            {

                    FastInput input = new FastInput(System.in);
                    PrintWriter output = new PrintWriter(System.out,true);

                    int n = input.readInt();
                    int steps=0,points =0;

                    Card[] array = new Card[n];

                    for(int i=0;i<n;++i)
                        array[i]= new Card(input.readInt() , input.readInt());

                    Arrays.sort(array);

                    for(int i=0;i<n;++i)
                    {
                            if(array[i].count>0)
                            {
                                    points+=array[i].point;
                                    steps += array[i].count;

                            }

                    }

                    if(steps==0)
                        steps=1;

                    for(int i=0;i<n;++i)
                    {
                            if(steps>0 && array[i].count==0)
                            {
                                points +=array[i].point;
                                --steps;
                            }

                    }

                    output.println(points);

                    input.close();
                    output.close();

            }
}

class Card implements Comparable<Card>
{
        int count;
        int point;

        Card(int point , int count)
        {
                this.count = count;
                this.point = point;

        }

        public int compareTo(Card x)
        {

                if(this.point > x.point)
                    return -1;
                else if(this.point == x.point)
                    return 0;
                else
                    return 1;

        }

}

class FastInput
{

        private InputStream stream;
        private byte[] buf = new byte[1024];
        private int curChar;
        private int numChars;

        public FastInput(InputStream userInputStream)
        {
            this.stream = userInputStream;

        }

        public int readChar()
        {

            if (numChars == -1)
                throw new InputMismatchException();

            if (curChar >= numChars)
            {

                curChar = 0;

                try
                {
                    numChars = stream.read(buf);
                }
                catch (IOException e)
                {
                    throw new InputMismatchException();
                }

                if (numChars <= 0)
                    return -1;

            }

            return buf[curChar++];

        }

        public boolean isSpaceChar(int c)
        {

                return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;

        }

        public int readInt()
        {

            int c = readChar();
            int sgn = 1;

            while (isSpaceChar(c))
                c = readChar();

            if (c == '-' )
            {
                sgn = -1;
                c = readChar();

            }

            int res = 0;

            do {

                if (c < '0' || c > '9')
                    throw new InputMismatchException();

                res *= 10;
                res += c - '0';
                c = readChar();

            } while (!isSpaceChar(c));

            return res * sgn;

        }

        public long readLong()
        {

            int c = readChar();
            int sgn = 1;

            while (isSpaceChar(c))
                c = readChar();

            if (c == '-' )
            {
                sgn = -1;
                c = readChar();

            }

            long res = 0;

            do {

                if (c < '0' || c > '9')
                    throw new InputMismatchException();

                res *= 10;
                res += c - '0';
                c = readChar();

            } while (!isSpaceChar(c));

            return res * sgn;

        }

        public String readString() {

            int c = readChar();

            while (isSpaceChar(c))
                c = readChar();

            StringBuilder res = new StringBuilder();

            do
            {

                res.append((char)c);
                c = readChar();

            } while (!isSpaceChar(c));

            return res.toString();

        }

        // The method created intially skips all whitespaces as defined above and then starts reading everything before \r , \n  , or both
        public String readLine()
        {
                int c=  readChar();

                while (isSpaceChar(c))
                    c = readChar();

                StringBuilder res = new StringBuilder();

                do
                {
                    res.append(c);
                    c = readChar();

                }while (c != '\r' &&  c!= '\n');

                return res.toString();

        }

        public void close()
        {
                try
                {
                    stream.close();
                }
                catch(IOException ex)
                {
                    ex.printStackTrace();

                }
        }

}


import java.io.IOException;
import java.io.OutputStreamWriter;
import java.util.Arrays;
import java.io.BufferedWriter;
import java.util.InputMismatchException;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.Writer;
import java.math.BigInteger;
import java.io.InputStream;

/**
 * Built using CHelper plug-in
 * Actual solution is at the top
 */
public class Main {
    public static void main(String[] args) {
        InputStream inputStream = System.in;
        OutputStream outputStream = System.out;
        InputReader in = new InputReader(inputStream);
        OutputWriter out = new OutputWriter(outputStream);
        TaskB solver = new TaskB();
        solver.solve(1, in, out);
        out.close();
    }
}

class TaskB {
    public void solve(int testNumber, InputReader in, OutputWriter out) {
        int n = in.readInt();
        Card[] cards = new Card[n];
        for (int i = 0; i < n; i++)
            cards[i] = new Card(in.readInt(), in.readInt());
        Arrays.sort(cards);
        int cnt = 1;
        int v = 0;
        int idx = 0;
        while (cnt > 0) {
            cnt--;
            v += cards[idx].a;
            cnt += cards[idx++].b;
        }
        out.printLine(v);
    }

    class Card implements Comparable<Card> {
        int a;
        int b;

        public Card(int a, int b) {
            this.a = a;
            this.b = b;
        }

        public int compareTo(Card card) {
            int c = Integer.valueOf(card.b).compareTo(this.b);
            return (c == 0 ? Integer.valueOf(card.a).compareTo(this.a) : c);
        }
    }
}

class InputReader {

    private InputStream stream;
    private byte[] buf = new byte[1024];
    private int curChar;
    private int numChars;
    private SpaceCharFilter filter;

    public InputReader(InputStream stream) {
        this.stream = stream;
    }

    public int read() {
        if (numChars == -1)
            throw new InputMismatchException();
        if (curChar >= numChars) {
            curChar = 0;
            try {
                numChars = stream.read(buf);
            } catch (IOException e) {
                throw new InputMismatchException();
            }
            if (numChars <= 0)
                return -1;
        }
        return buf[curChar++];
    }

    public int readInt() {
        int c = read();
        while (isSpaceChar(c))
            c = read();
        int sgn = 1;
        if (c == '-') {
            sgn = -1;
            c = read();
        }
        int res = 0;
        do {
            if (c < '0' || c > '9')
                throw new InputMismatchException();
            res *= 10;
            res += c - '0';
            c = read();
        } while (!isSpaceChar(c));
        return res * sgn;
    }

    public boolean isSpaceChar(int c) {
        if (filter != null)
            return filter.isSpaceChar(c);
        return isWhitespace(c);
    }

    public static boolean isWhitespace(int c) {
        return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
    }

    public interface SpaceCharFilter {
        public boolean isSpaceChar(int ch);
    }
}

class OutputWriter {
    private final PrintWriter writer;

    public OutputWriter(OutputStream outputStream) {
        writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream)));
    }

    public OutputWriter(Writer writer) {
        this.writer = new PrintWriter(writer);
    }

    public void print(Object...objects) {
        for (int i = 0; i < objects.length; i++) {
            if (i != 0)
                writer.print(' ');
            writer.print(objects[i]);
        }
    }

    public void printLine(Object...objects) {
        print(objects);
        writer.println();
    }

    public void close() {
        writer.close();
    }

}


import java.io.IOException;
import java.io.OutputStreamWriter;
import java.util.Arrays;
import java.io.BufferedWriter;
import java.util.InputMismatchException;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.Writer;
import java.math.BigInteger;
import java.io.InputStream;

/**
 * Built using CHelper plug-in
 * Actual solution is at the top
 */
public class Main {
    public static void main(String[] args) {
        InputStream inputStream = System.in;
        OutputStream outputStream = System.out;
        InputReader in = new InputReader(inputStream);
        OutputWriter out = new OutputWriter(outputStream);
        TaskB solver = new TaskB();
        solver.solve(1, in, out);
        out.close();
    }
}

class TaskB {
    public void solve(int testNumber, InputReader in, OutputWriter out) {
        int n = in.readInt();
        Card[] cards = new Card[n];
        for (int i = 0; i < n; i++)
            cards[i] = new Card(in.readInt(), in.readInt());
        Arrays.sort(cards);
        int cnt = 1;
        int v = 0;
        int idx = 0;
        while (cnt > 0 && idx < n) {
            cnt--;
            v += cards[idx].a;
            cnt += cards[idx++].b;
        }
        out.printLine(v);
    }

    class Card implements Comparable<Card> {
        int a;
        int b;

        public Card(int a, int b) {
            this.a = a;
            this.b = b;
        }

        public int compareTo(Card card) {
            int c = Integer.valueOf(card.b).compareTo(this.b);
            return (c == 0 ? Integer.valueOf(card.a).compareTo(this.a) : c);
        }
    }
}

class InputReader {

    private InputStream stream;
    private byte[] buf = new byte[1024];
    private int curChar;
    private int numChars;
    private SpaceCharFilter filter;

    public InputReader(InputStream stream) {
        this.stream = stream;
    }

    public int read() {
        if (numChars == -1)
            throw new InputMismatchException();
        if (curChar >= numChars) {
            curChar = 0;
            try {
                numChars = stream.read(buf);
            } catch (IOException e) {
                throw new InputMismatchException();
            }
            if (numChars <= 0)
                return -1;
        }
        return buf[curChar++];
    }

    public int readInt() {
        int c = read();
        while (isSpaceChar(c))
            c = read();
        int sgn = 1;
        if (c == '-') {
            sgn = -1;
            c = read();
        }
        int res = 0;
        do {
            if (c < '0' || c > '9')
                throw new InputMismatchException();
            res *= 10;
            res += c - '0';
            c = read();
        } while (!isSpaceChar(c));
        return res * sgn;
    }

    public boolean isSpaceChar(int c) {
        if (filter != null)
            return filter.isSpaceChar(c);
        return isWhitespace(c);
    }

    public static boolean isWhitespace(int c) {
        return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
    }

    public interface SpaceCharFilter {
        public boolean isSpaceChar(int ch);
    }
}

class OutputWriter {
    private final PrintWriter writer;

    public OutputWriter(OutputStream outputStream) {
        writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream)));
    }

    public OutputWriter(Writer writer) {
        this.writer = new PrintWriter(writer);
    }

    public void print(Object...objects) {
        for (int i = 0; i < objects.length; i++) {
            if (i != 0)
                writer.print(' ');
            writer.print(objects[i]);
        }
    }

    public void printLine(Object...objects) {
        print(objects);
        writer.println();
    }

    public void close() {
        writer.close();
    }

}


import java.io.BufferedInputStream;
import java.util.Arrays;
import java.util.Scanner;

public class B_155_Combination {
	public static void main(String[] args) {
		Scanner sc = new Scanner(new BufferedInputStream(System.in));
		int n = sc.nextInt();
		card[] array = new card[n];
		for (int i = 0; i < n; i++) {
			int a = sc.nextInt();
			int b = sc.nextInt();
			card temp = new card(a, b);
			array[i] = temp;
		}
		Arrays.sort(array);
		int counter = 1;
		int points = 0;
		int cardsPlayed = 0;
		for (int i = array.length - 1; i >= 0 && counter > 0; i--) {
			cardsPlayed++;
			points += array[i].a;
			counter = counter - 1 + array[i].b;
		}
		System.out.println(points);
	}
}

class card implements Comparable {
	int a, b;

	public card(int aa, int bb) {
		this.a = aa;
		this.b = bb;
	}

	public String toString() {
		return "a: " + this.a + " b " + this.b;
	}

	public int compareTo(Object arg0) {
		card two = (card) arg0;
		if (this.b > two.b)
			return 1;
		else if (this.b < two.b)
			return -1;
		else if (this.b == two.b) {
			if (this.a > two.a)
				return 1;
			else if (this.a == two.a)
				return 0;
			else if (this.a < two.a)
				return -1;
		}
		return 0;
	}
}


import java.io.*;
import java.util.*;
import java.math.*;

public class Main{
    static class Card implements Comparable<Card>{
        int a, b;
        Card(int a, int b){
            this.a = a;
            this.b = b;
        }
        public int compareTo(Card sec){
            if(this.b < sec.b)
                return -1;
            if(this.b > sec.b)
                return 1;
            if(this.a < sec.a)
                return -1;
            if(this.a > sec.a)
                return 1;
            return 0;
        }
    }
    public static void main(String[] args)throws Throwable{
        Escanner sc = new Escanner();
        out = new PrintWriter(System.out);
        ///////////
        int n = sc.nextInt();
        Card[] card = new Card[n];
        for(int i=0; i<n; i++)
            card[i] = new Card(sc.nextInt(), sc.nextInt());
        Arrays.sort(card);
        int score = 0;
        int cnt = 1;
        for(int i=n-1; i>=0; i--){
            cnt--;
            cnt+=card[i].b;
            score+=card[i].a;
            if(cnt==0)
                break;
        }
        out.println(score);
        //////////
        out.close();
    }
    static PrintWriter out;

    static class Escanner {
        BufferedReader in;
        StringTokenizer st;

        Escanner() throws Throwable {
            in = new BufferedReader(new InputStreamReader(System.in),32768);
            st = new StringTokenizer("");
        }

        String nextStr() throws Throwable {
            while(!st.hasMoreTokens())
                st = new StringTokenizer(in.readLine(), " ,.:;");
            return st.nextToken();
        }

        int nextInt() throws Throwable {
            return Integer.parseInt(nextStr());
        }

        long nextLong() throws Throwable {
            return Long.parseLong(nextStr());
        }

        BigInteger nextBigInt() throws Throwable {
            return new BigInteger(nextStr());
        }

        double nextDouble() throws Throwable {
            return Double.parseDouble(nextStr());
        }
    }
}


import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.StringTokenizer;

public class B {

    static BufferedReader in;
    static StringTokenizer st;
    static PrintWriter out;

    static String next() throws IOException {
        while (st == null || !st.hasMoreTokens()) {
            st = new StringTokenizer(in.readLine());
        }
        return st.nextToken();
    }

    static int nextInt() throws IOException {
        return Integer.parseInt(next());
    }

    static class Card implements Comparable<Card> {

        int point;
        int step;

        public Card(int p, int s) {
            this.point = p;
            this.step = s;
        }

        public int compareTo(Card that) {
            if (this.step < that.step
                    || (this.step == that.step && this.point < that.point)) {
                return 1;
            }
            return -1;
        }
    }

    public static void main(String[] args) throws IOException {
        in = new BufferedReader(new InputStreamReader(System.in));
        out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(
                System.out)));
        int n = nextInt();
        int ans = 0;
        Card[] cards = new Card[n];
        for (int i = 0; i < n; i++) {
            cards[i] = new Card(nextInt(), nextInt());
        }
        Arrays.sort(cards);
        int tmp = 1;
        for (int i = 0; i < n; i++) {
            if (tmp <= 0) {
                break;
            }
            ans += cards[i].point;
            tmp += cards[i].step;
            tmp--;
        }
        out.print(ans);
        out.close();
    }
}


import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.StringTokenizer;

public class B {

    static BufferedReader in;
    static StringTokenizer st;
    static PrintWriter out;

    static String next() throws IOException {
        while (st == null || !st.hasMoreTokens()) {
            st = new StringTokenizer(in.readLine());
        }
        return st.nextToken();
    }

    static int nextInt() throws IOException {
        return Integer.parseInt(next());
    }

    static class Card implements Comparable<Card> {

        int point;
        int step;

        public Card(int p, int s) {
            this.point = p;
            this.step = s;
        }

        public int compareTo(Card that) {
            if (this.step > that.step) {
                return -(this.step - that.step);
            } else if (this.step == that.step) {
                return -(this.point - that.point);
            }
            return 0;
        }

    }

    public static void main(String[] args) throws IOException {
        in = new BufferedReader(new InputStreamReader(System.in));
        out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(
                System.out)));
        int n = nextInt();
        int ans = 0;
        Card[] cards = new Card[n + 1];
        for (int i = 0; i < n; i++) {
            cards[i] = new Card(nextInt(), nextInt());
        }
        Arrays.sort(cards, 0, n);
        int tmp = 1;
        for (int i = 0; i < n; i++) {
            if (tmp <= 0) {
                break;
            }
            ans += cards[i].point;
            tmp += cards[i].step;
            tmp--;
        }
        out.print(ans);
        out.close();
    }
}


import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.Comparator;
import java.util.Scanner;

public class Main {

    private static final InputStreamReader standardInput = new InputStreamReader(System.in);
    private static final BufferedReader bufferedReader = new BufferedReader(standardInput);
    private static final Scanner scanner = new Scanner(bufferedReader);

    private static final OutputStreamWriter standardOutput = new OutputStreamWriter(System.out);
    private static final BufferedWriter bufferedWriter = new BufferedWriter(standardOutput);
    private static final PrintWriter printWriter = new PrintWriter(bufferedWriter);

    public static void main(String[] args) {
        int n = scanner.nextInt();
        Pair[] cards = new Pair[n];
        for (int i = 0; i < n; i++) {
            int a = scanner.nextInt();
            int b = scanner.nextInt();
            cards[i] = new Pair(a, b);
        }
        printWriter.println(getMaxPoints(n, cards));
        printWriter.flush();
        scanner.close();
    }

    private static long getMaxPoints(int n, Pair[] cards) {
        Arrays.sort(cards, new Comparator<Pair>() {

            @Override
            public int compare(Pair p1, Pair p2) {
                if (p1.getB() > p2.getB()) {
                    return -1;
                } else if (p1.getB() < p2.getB()) {
                    return 1;
                } else if (p1.getA() >= p2.getA()) {
                    return -1;
                } else {
                    return 1;
                }
            }
        });

        long points = 0;
        int b = 1;
        int ptr = 0;
        while (ptr < n && b > 0) {
            points += cards[ptr].getA();
            b--;
            b += cards[ptr].getB();
            ptr++;
        }

        return points;
    }
}

class Pair {

    private final int a, b;

    public Pair(int a, int b) {
        this.a = a;
        this.b = b;
    }

    public int getA() {
        return this.a;
    }

    public int getB() {
        return this.b;
    }
}


import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.Comparator;
import java.util.Scanner;

public class Main {

    private static final InputStreamReader standardInput = new InputStreamReader(System.in);
    private static final BufferedReader bufferedReader = new BufferedReader(standardInput);
    private static final Scanner scanner = new Scanner(bufferedReader);

    private static final OutputStreamWriter standardOutput = new OutputStreamWriter(System.out);
    private static final BufferedWriter bufferedWriter = new BufferedWriter(standardOutput);
    private static final PrintWriter printWriter = new PrintWriter(bufferedWriter);

    public static void main(String[] args) {
        int n = scanner.nextInt();
        Pair[] cards = new Pair[n];
        for (int i = 0; i < n; i++) {
            int a = scanner.nextInt();
            int b = scanner.nextInt();
            cards[i] = new Pair(a, b);
        }
        printWriter.println(getMaxPoints(n, cards));
        printWriter.flush();
        scanner.close();
    }

    private static long getMaxPoints(int n, Pair[] cards) {
        Arrays.sort(cards, new Comparator<Pair>() {

            @Override
            public int compare(Pair p1, Pair p2) {
                if (p1.getB() > p2.getB()) {
                    return -1;
                } else if (p1.getB() < p2.getB()) {
                    return 1;
                } else if (p1.getA() >= p1.getA()) {
                    return -1;
                } else {
                    return 1;
                }
            }
        });

        long points = 0;
        int b = 1;
        int ptr = 0;
        while (ptr < n && b > 0) {
            points += cards[ptr].getA();
            b--;
            b += cards[ptr].getB();
            ptr++;
        }

        return points;
    }
}

class Pair {

    private final int a, b;

    public Pair(int a, int b) {
        this.a = a;
        this.b = b;
    }

    public int getA() {
        return this.a;
    }

    public int getB() {
        return this.b;
    }
}


import java.util.*;
public class Main{
public static void main(String... args){
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int[][] t = new int[n][2];
for (int i=0; i<n; i++){
  t[i][0]=sc.nextInt();
  t[i][1]=sc.nextInt();
}
Arrays.sort(t, new Comparator<int[]>(){public int compare(int[]a,int[]b){
if (a[1]>b[1]) return -1;
if (a[1]<b[1]) return 1;
if (a[0]>b[0]) return -1;
if (a[0]<b[0]) return 1;
return 0;
}});
int moves = 1;
long sum = 0;
int i=0;
while (moves>0 && i<n){
  moves+=t[i][1];
  sum+=t[i][0];
  moves--;
  i++;
}
System.out.println(sum);

}
}


import java.io.*;
import java.util.*;

public class Codeforces {

    public static void main(String[] args) throws IOException {
        Reader.init(System.in);
        int n = Reader.nextInt();
        Card[] arr = new Card[n];

        for(int i = 0; i < n; i++){
            arr[i] = new Card(Reader.nextInt(), Reader.nextInt());
        }

        Arrays.sort(arr);
        int counter = 1, points = 0;

        for(int i = 0; i < n; i++){
            counter += arr[i].buttom;
            points += arr[i].top;

            if(--counter == 0)
                break;
        }

        System.out.println(points);
    }

}

class Card implements Comparable<Card>{

    int top;
    int buttom;

    public Card(int top, int buttom){
        this.top = top;
        this.buttom = buttom;
    }

    @Override
    public int compareTo(Card t) {
        int x = t.buttom - this.buttom;
        if(x == 0)
            return t.top - this.top;
        return x;
    }

}

class Reader {

    static BufferedReader reader;
    static StringTokenizer tokenizer;

    /**
     * call this method to initialize reader for InputStream
     */
    static void init(InputStream input) {
        reader = new BufferedReader(
                new InputStreamReader(input));
        tokenizer = new StringTokenizer("");
    }

    /**
     * get next word
     */
    static String next() throws IOException {
        while (!tokenizer.hasMoreTokens()) {
            //TODO add check for eof if necessary
            tokenizer = new StringTokenizer(
                    reader.readLine());
        }
        return tokenizer.nextToken();
    }

    static int nextInt() throws IOException {
        return Integer.parseInt(next());
    }

    static byte nextByte() throws IOException {
        return Byte.parseByte(next());
    }

    static long nextLong() throws IOException {
        return Long.parseLong(next());
    }

    static double nextDouble() throws IOException {
        return Double.parseDouble(next());
    }
}


import java.io.*;
import java.util.*;

public class Main  {

    public static void main(String args[]) throws IOException {

            Reader.init(System.in);
            int n=Reader.nextInt();
            int b[][]=new int[n][2];
            for (int i = 0; i < n; i++) {
                for (int j = 0; j < 2; j++) {
                 b[i][j]=Reader.nextInt();
        }
            }

                      Arrays.sort(b, new Comparator() {
    public int compare(Object o1, Object o2) {
        int[] elt1 = (int[])o1;
        int[] elt2 = (int[])o2;
        if(Integer.valueOf(elt1[1]+"")>Integer.valueOf(elt2[1]+""))
            return Integer.valueOf(elt2[1]+"");
        if(Integer.valueOf(elt1[1]+"")<Integer.valueOf(elt2[1]+""))
            return Integer.valueOf(elt1[1]+"");

        return Integer.valueOf(elt1[0]+"").compareTo(Integer.valueOf(elt2[0]+""));
    }
});

            int res = 0, count = 1;
		for(int i=n-1; i>=0 && count > 0; --i,--count) {
			res += b[i][0];
			count += b[i][1];
		}
                System.out.println(res);
    }

}
class Reader {

    static BufferedReader reader;
    static StringTokenizer tokenizer;

    /**
     * call this method to initialize reader for InputStream
     */
    static void init(InputStream input) {
        reader = new BufferedReader(
                new InputStreamReader(input));
        tokenizer = new StringTokenizer("");
    }

    /**
     * get next word
     */
    static String next() throws IOException {
        while (!tokenizer.hasMoreTokens()) {
            //TODO add check for eof if necessary
            tokenizer = new StringTokenizer(
                    reader.readLine());
        }
        return tokenizer.nextToken();
    }

    static int nextInt() throws IOException {
        return Integer.parseInt(next());
    }

    static long nextLong() throws IOException {
        return Long.parseLong(next());
    }

    static double nextDouble() throws IOException {
        return Double.parseDouble(next());
    }

    static public void nextIntArrays(int[]... arrays) throws IOException {
        for (int i = 1; i < arrays.length; ++i) {
            if (arrays[i].length != arrays[0].length) {
                throw new InputMismatchException("Lengths are different");
            }
        }
        for (int i = 0; i < arrays[0].length; ++i) {
            for (int[] array : arrays) {
                array[i] = nextInt();
            }
        }
    }

    static public void nextLineArrays(String[]... arrays) throws IOException {
        for (int i = 1; i < arrays.length; ++i) {
            if (arrays[i].length != arrays[0].length) {
                throw new InputMismatchException("Lengths are different");
            }
        }
        for (int i = 0; i < arrays[0].length; ++i) {
            for (String[] array : arrays) {
                array[i] = reader.readLine();
            }
        }
    }
}


import java.io.*;
import java.util.*;

public class Main {

    public static void main(String args[]) throws IOException {

        Reader.init(System.in);

        ArrayList<V> v = new ArrayList<>();

        int n = Reader.nextInt();

        for (int i = 0; i < n; i++)
            v.add(new V(Reader.nextInt(), Reader.nextInt()));

        Collections.sort(v);

        int res = v.get(0).a;
        int counter = v.get(0).b;
        for (int i = 0; i < counter && i < v.size()-1 ; i++) {
            V C = v.get(i + 1);
            res += C.a;
            counter = counter + C.b;
        }
        System.out.println(res);
    }

}

class V implements Comparable<V> {

    int a;
    int b;

    public V(Integer c, Integer d) {
        a = c;
        b = d;
    }

    public int compareTo(V o) {
        return (o.b - b == 0) ? (o.a - a) : (o.b - b);
    }

}

class Reader {

    static BufferedReader reader;
    static StringTokenizer tokenizer;

    /**
     * call this method to initialize reader for InputStream
     */
    static void init(InputStream input) {
        reader = new BufferedReader(
                new InputStreamReader(input));
        tokenizer = new StringTokenizer("");
    }

    /**
     * get next word
     */
    static String next() throws IOException {
        while (!tokenizer.hasMoreTokens()) {
            //TODO add check for eof if necessary
            tokenizer = new StringTokenizer(
                    reader.readLine());
        }
        return tokenizer.nextToken();
    }

    static int nextInt() throws IOException {
        return Integer.parseInt(next());
    }

    static long nextLong() throws IOException {
        return Long.parseLong(next());
    }

    static double nextDouble() throws IOException {
        return Double.parseDouble(next());
    }

    static public void nextIntArrays(int[]... arrays) throws IOException {
        for (int i = 1; i < arrays.length; ++i) {
            if (arrays[i].length != arrays[0].length) {
                throw new InputMismatchException("Lengths are different");
            }
        }
        for (int i = 0; i < arrays[0].length; ++i) {
            for (int[] array : arrays) {
                array[i] = nextInt();
            }
        }
    }

    static public void nextLineArrays(String[]... arrays) throws IOException {
        for (int i = 1; i < arrays.length; ++i) {
            if (arrays[i].length != arrays[0].length) {
                throw new InputMismatchException("Lengths are different");
            }
        }
        for (int i = 0; i < arrays[0].length; ++i) {
            for (String[] array : arrays) {
                array[i] = reader.readLine();
            }
        }
    }
}


import java.io.*;
import java.util.*;

public class Main {

    public static void main(String args[]) throws IOException {

        Reader.init(System.in);

        ArrayList<V> v = new ArrayList<>();

        int n = Reader.nextInt();

        for (int i = 0; i < n; i++)
            v.add(new V(Reader.nextInt(), Reader.nextInt()));

        Collections.sort(v);

        int res = v.get(0).a;
        int counter = v.get(0).b;
        for (int i = 0; i < counter && i < v.size() ; i++) {
            V C = v.get(i + 1);
            res += C.a;
            counter = counter + C.b;
        }
        System.out.println(res);
    }

}

class V implements Comparable<V> {

    int a;
    int b;

    public V(Integer c, Integer d) {
        a = c;
        b = d;
    }

    public int compareTo(V o) {
        return (o.b - b == 0) ? (o.a - a) : (o.b - b);
    }

}

class Reader {

    static BufferedReader reader;
    static StringTokenizer tokenizer;

    /**
     * call this method to initialize reader for InputStream
     */
    static void init(InputStream input) {
        reader = new BufferedReader(
                new InputStreamReader(input));
        tokenizer = new StringTokenizer("");
    }

    /**
     * get next word
     */
    static String next() throws IOException {
        while (!tokenizer.hasMoreTokens()) {
            //TODO add check for eof if necessary
            tokenizer = new StringTokenizer(
                    reader.readLine());
        }
        return tokenizer.nextToken();
    }

    static int nextInt() throws IOException {
        return Integer.parseInt(next());
    }

    static long nextLong() throws IOException {
        return Long.parseLong(next());
    }

    static double nextDouble() throws IOException {
        return Double.parseDouble(next());
    }

    static public void nextIntArrays(int[]... arrays) throws IOException {
        for (int i = 1; i < arrays.length; ++i) {
            if (arrays[i].length != arrays[0].length) {
                throw new InputMismatchException("Lengths are different");
            }
        }
        for (int i = 0; i < arrays[0].length; ++i) {
            for (int[] array : arrays) {
                array[i] = nextInt();
            }
        }
    }

    static public void nextLineArrays(String[]... arrays) throws IOException {
        for (int i = 1; i < arrays.length; ++i) {
            if (arrays[i].length != arrays[0].length) {
                throw new InputMismatchException("Lengths are different");
            }
        }
        for (int i = 0; i < arrays[0].length; ++i) {
            for (String[] array : arrays) {
                array[i] = reader.readLine();
            }
        }
    }
}


import java.io.IOException;
import java.util.Arrays;
import java.util.Comparator;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.InputStream;

/**
 * Built using CHelper plug-in
 * Actual solution is at the top
 * @author Mahmoud Aladdin <aladdin3>
 */
public class Main {
	public static void main(String[] args) {
		InputStream inputStream = System.in;
		OutputStream outputStream = System.out;
		InputReader in = new InputReader(inputStream);
		PrintWriter out = new PrintWriter(outputStream);
		TaskB solver = new TaskB();
		solver.solve(1, in, out);
		out.close();
	}
}

class TaskB {
    public void solve(int testNumber, InputReader jin, PrintWriter jout) {
        int n = jin.integer();
        Card[] array = new Card[n];
        for(int i = 0; i < n; i++) {
            array[i] = new Card();
            array[i].a = jin.integer();
            array[i].b = jin.integer();
        }
        Arrays.sort(array, new Comparator<Card>() {
            @Override
            public int compare(Card o1, Card o2) {
                if(o1.b == o2.b) return o2.a - o1.a;
                return o2.b - o1.b;
            }
        });
        int i = -1;
        int score = 0;
        int c = 1;
        while(c-- > 0 && ++i < n) {
            score += array[i].a;
            c += array[i].b;
        }
        jout.println(score);

    }

    class Card {
        int a = 0;
        int b = 0;
    }
}

class InputReader {
    private static final int bufferMaxLength = 1024;
    private InputStream in;
    private byte[] buffer;
    private int currentBufferSize;
    private int currentBufferTop;
    private static final String tokenizers = " \t\r\f\n";

    public InputReader(InputStream stream) {
        this.in = stream;
        buffer = new byte[bufferMaxLength];
        currentBufferSize = 0;
        currentBufferTop = 0;
    }

    private boolean refill() {
        try {
            this.currentBufferSize = this.in.read(this.buffer);
            this.currentBufferTop = 0;
        } catch(Exception e) {}
        return this.currentBufferSize > 0;
    }

    private Byte readChar() {
        if(currentBufferTop < currentBufferSize) {
            return this.buffer[this.currentBufferTop++];
        } else {
            if(!this.refill()) {
                return null;
            } else {
                return readChar();
            }
        }
    }

    public String token()  {
        StringBuffer tok = new StringBuffer();
        Byte first;
        while((first = readChar()) != null && (tokenizers.indexOf((char) first.byteValue()) != -1));
        if(first == null) return null;
        tok.append((char)first.byteValue());
        while((first = readChar()) != null && (tokenizers.indexOf((char) first.byteValue()) == -1)) {
            tok.append((char)first.byteValue());
        }
        return tok.toString();
    }

    public Integer integer() throws NumberFormatException {
        String tok = token();
        return tok == null? null : Integer.parseInt(tok);
    }

    }


import java.awt.Point;
import java.util.Comparator;
import java.util.PriorityQueue;
import java.util.Scanner;

public class B {
    public static void main(String[] args) {
        Scanner sc=new Scanner(System.in);
        int n=sc.nextInt();
        PriorityQueue<Point> pq=new PriorityQueue<Point>(n, new Comparator<Point>() {
            public int compare(Point p1,Point p2){
                if(p2.y>p1.y) return 1;
                else if(p2.y<p1.y) return -1;
                else{
                    if(p2.x>p1.x) return 1;
                    else if(p2.x<p1.x) return -1;
                    return 0;
                }
            }
        });
        for(int i=0;i<n;i++){
            pq.add(new Point(sc.nextInt(),sc.nextInt()));
        }
        int curAvail=1;
        int res=0;
        while(curAvail>0&&!pq.isEmpty()){
            Point tmp=pq.remove();
            curAvail-=1;
            curAvail+=tmp.y;
            res+=tmp.x;
        }
        System.out.println(res);
    }
}


import java.util.*;
public class Combination {
    public static void main(String[] Args){
        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt();
        int tot = 0;
        int canp = 1;
        PriorityQueue<Integer> pq = new PriorityQueue<Integer>();
        for(int k =0;k<n;k++){
            int x = sc.nextInt();
            int y = sc.nextInt();
            if(y!=0){
                canp+=y-1;
                tot+=x;
            }
            else
                pq.add(-x);
        }
        while(canp>0&&!pq.isEmpty()){
            tot+=Math.max(-pq.poll(),0);
            canp--;
        }
        System.out.println(tot);
    }
}


import java.util.*;
import java.io.*;
public class Main {

	public static void main(String[] args) throws Exception {
		BufferedReader bf = new BufferedReader(new InputStreamReader(System.in));
		int size = Integer.parseInt(bf.readLine());
		ArrayList<carta> cartas = new ArrayList<carta>();
		for (int i = 0; i < size; i++) {
			String[] cads = bf.readLine().split(" ");
			cartas.add(new carta(Integer.parseInt(cads[0]),Integer.parseInt(cads[1])));
		};
		Collections.sort(cartas,new carta());
		int cant = cartas.get(0).y+1;
		int cuenta = cartas.get(0).x;
		for (int i = 1; i < ((cant>=size)?size:cant) ; i++) {
			cant+=cartas.get(i).y;
			cuenta+=cartas.get(i).x;
		}
		System.out.println(cuenta);
	}

}
class carta implements Comparator<carta>{
	int x,y;
	public carta(){}
	public carta(int x,int y){
		this.x=x;
		this.y=y;
	}
	@Override
	public int compare(carta o1, carta o2) {
		int result=0;
		if(o1.y<o2.y)
			result=1;
		if(o1.y==o2.y)
			result=(o1.x==o2.x)?0:(o1.x>o2.y)?-1:1;
		if(o1.y>o2.y)
			result=-1;

		return result;
	}
	public String toString() {
		return "carta [x=" + x + ", y=" + y + "]";
	}

}


import java.util.*;
import java.io.*;
public class Main {

	public static void main(String[] args) throws Exception {
		BufferedReader bf = new BufferedReader(new InputStreamReader(System.in));
		int size = Integer.parseInt(bf.readLine());
		ArrayList<carta> cartas = new ArrayList<carta>();
		for (int i = 0; i < size; i++) {
			String[] cads = bf.readLine().split(" ");
			cartas.add(new carta(Integer.parseInt(cads[0]),Integer.parseInt(cads[1])));
		};
		Collections.sort(cartas,new carta());
		int cant = cartas.get(0).y+1;
		int cuenta = cartas.get(0).x;
		for (int i = 1; i < ((cant>=size)?size:cant) ; i++) {
			cant+=cartas.get(i).y;
			cuenta+=cartas.get(i).x;
		}
		System.out.println(cuenta);
	}

}
class carta implements Comparator<carta>{
	int x,y;
	public carta(){}
	public carta(int x,int y){
		this.x=x;
		this.y=y;
	}
	@Override
	public int compare(carta o1, carta o2) {
		int result=0;
		if(o1.y<o2.y)
			result=1;
		if(o1.y==o2.y)
			result=(o1.x==o2.x)?0:(o1.x>o2.x)?-1:1;
		if(o1.y>o2.y)
			result=-1;

		return result;
	}
	public String toString() {
		return "carta [x=" + x + ", y=" + y + "]";
	}

}


//package hellolinux;

import java.util.Scanner;

public class HelloLinux {

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int n = sc.nextInt();
        int moves = 1;
        int points = 0;
        int counter = 0;
        int c = 0;
        int[] cards = new int[n];
        for (int i = 0; i < n; i++) {
            int p = sc.nextInt();
            int m = sc.nextInt();
            if (m == 0) {
                cards[counter] = p;
                counter++;
            } else {
                points += p;
                moves += m - 1;
            }
        }
        while (c < counter - 1) {
            if (cards[c] < cards[c + 1]) {
                int temp = cards[c];
                cards[c] = cards[c + 1];
                cards[c + 1] = temp;
                c = -1;
            }
            c++;
        }
        c = 0;
        while (c < counter && moves > 0) {
            points += cards[c];
            moves--;
            c++;
        }
        System.out.println(points);
    }
}


import java.io.*;
import java.util.*;
public final class combination
{
	static Scanner sc=new Scanner(System.in);
	static PrintWriter out=new PrintWriter(System.out);

	public static void main(String args[]) throws Exception
	{
		int n=sc.nextInt();
		Card[] a=new Card[n];
		for(int i=0;i<n;i++)
		{
			a[i]=new Card(sc.nextInt(),sc.nextInt());
		}
		Arrays.sort(a);
		for(int i=0;i<n;i++)
		{
			for(int j=i+1;j<n;j++)
			{
				if(a[i].chances==a[j].chances && a[i].val>a[j].val)
				{
					Card temp=a[i];
					a[i]=a[j];
					a[j]=temp;
				}
			}
		}
		int i=n-1;
		long pts=0;
		int c=1;
		while(i>=0)
		{
			pts+=a[i].val;
			c--;
			c+=a[i].chances;
			if(c==0)
			{
				break;
			}
			i--;
		}
		out.println(pts);
		out.close();
	}
}
class Card implements Comparable<Card>
{
	int val,chances;
	public Card(int val,int chances)
	{
		this.val=val;
		this.chances=chances;
	}
	public int compareTo(Card x)
	{
		return Integer.compare(this.chances,x.chances);
	}
}


import java.io.*;
import java.io.PrintWriter;
import java.util.*;
import java.io.InputStream;
import java.io.DataInputStream;

public class Main
{
 // static{ System.out.println("hello");}
        static InputStream inputStream = System.in;
        static OutputStream outputStream = System.out;
        static FastReader scn = new FastReader(inputStream);
        static PrintWriter out = new PrintWriter(outputStream);
        static int fibo[]=new int[61];
        static int start;
        static void print(int a[])
         {        for (int i=0;i<a.length ;i++)
               {
                    out.print(a[i]+" ");
               }
        }

        public static void main(String[] args) throws IOException
       {    int n=scn.ni();
           num arr[]=new num[n];
           for(int i =0 ;i<n;i++)
           {
              int a=scn.ni();
               int b=scn.ni();
                arr[i]=new num(a,b);
            }
            Arrays.sort(arr,new num());
            long sum=0;
            int cnt=1; int l=0;
            while(cnt!=0 && l<n)
            {
                sum+=arr[l].ff; cnt--;
                cnt+=arr[l].ss;

                l++;
            }
            out.println(sum);
             out.close();
        }

}

  class num implements Comparator<num>
    {

        public int ff;
        public int ss;

        num()
        {

        }
        num(int x,int y)
        {
            this.ff = x;
            this.ss =y;

        }
        public int getff()
        {
        return ff;
        }
        public int getss()
        {
        return ss;
        }
       public boolean equals(Object n1)
        {num n=(num)n1;
        if (this.ff==n.ff && this.ss==n.ss) return true;
        else return false;

        }
        public int compare(num n1,num n2)
        {  if (n1.ss!=n2.ss) return n2.ss-n1.ss;
            else return n2.ff-n1.ff;

        }
    }

class FastReader
{

    public InputStream stream;
    private byte[] buf = new byte[1024];
    private int curChar;
    private int numChars;
    private SpaceCharFilter filter;

    public FastReader(InputStream stream)
    {
        this.stream = stream;
    }

    public int read()
    {
        if (numChars == -1)
        {
            throw new InputMismatchException ();
        }
        if (curChar >= numChars)
        {
            curChar = 0;
            try
            {
                numChars = stream.read (buf);
            } catch (IOException e)
            {
                throw new InputMismatchException ();
            }
            if (numChars <= 0)
            {
                return -1;
            }
        }
        return buf[curChar++];
    }

 public char nc()
    {
        int c = read ();
        while (isSpaceChar (c))
            c = read ();
        return (char) c;
    }

    public int ni()
    {
        int c = read ();
        while (isSpaceChar (c))
            c = read ();
        int sgn = 1;
        if (c == '-')
        {
            sgn = -1;
            c = read ();
        }
        int res = 0;
        do
        {
            if (c < '0' || c > '9')
            {

            }
            res *= 10;
            res += c - '0';
            c = read ();
        } while (!isSpaceChar (c));
        return res * sgn;
    }

    public long nl()
    {
        int c = read ();
        while (isSpaceChar (c))
            c = read ();
        int sgn = 1;
        if (c == '-')
        {
            sgn = -1;
            c = read ();
        }
        long res = 0;
        do
        {
            if (c < '0' || c > '9')
            {
                throw new InputMismatchException ();
            }
            res *= 10;
            res += c - '0';
            c = read ();
        } while (!isSpaceChar (c));
        return res * sgn;
    }

    public String ns()
    {
        int c = read ();
        while (isSpaceChar (c))
            c = read ();
        StringBuilder res = new StringBuilder ();
        do
        {
            res.appendCodePoint (c);
            c = read ();
        } while (!isSpaceChar (c));
        return res.toString ();
    }

    public boolean isSpaceChar(int c)
    {
        if (filter != null)
        {
            return filter.isSpaceChar (c);
        }
        return isWhitespace (c);
    }

    public static boolean isWhitespace(int c)
    {
        return c==' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
    }

    public String next()
    {
        return ns ();
    }

    public interface SpaceCharFilter
    {
        public boolean isSpaceChar(int ch);
    }
}


import java.util.Arrays;
import java.util.Scanner;

public class D {
    public static void main(String[] args) {
        Scanner in=new Scanner(System.in);
        int n = in.nextInt();
        int a[][] = new int[n][2];
        for(int i=0;i<n;i++){
        	a[i][0] = in.nextInt(); a[i][1] = in.nextInt();
        }
        int tempA,tempB;
        for(int i=0;i<n-1;i++){
        	for(int j=i+1;j<n;j++){
        		if(a[i][1]>a[j][1]){
        		tempA = a[i][0];
        		tempB = a[i][1];
        		a[i][0] = a[j][0];
        		a[i][1] = a[j][1];
        		a[j][0] = tempA;
        		a[j][1] = tempB;
        		}
        		else if(a[i][1]==a[j][1] && a[i][0]>a[j][0]){
        			tempA = a[i][0];
            		tempB = a[i][1];
            		a[i][0] = a[j][0];
            		a[i][1] = a[j][1];
            		a[j][0] = tempA;
            		a[j][1] = tempB;
        		}

        	}
        }
        int max = 0;
        int count = 1;
        while(count>0 && n>=0){
        	count += a[n-1][1];
        	count--;
        	max += a[n-1][0];
        	n--;
        }
        System.out.println(max);

    }
}


import java.util.Arrays;
import java.util.Scanner;

public class D {
    public static void main(String[] args) {
        Scanner in=new Scanner(System.in);
        int n = in.nextInt();
        int a[][] = new int[n][2];
        for(int i=0;i<n;i++){
        	a[i][0] = in.nextInt(); a[i][1] = in.nextInt();
        }
        int tempA,tempB;
        for(int i=0;i<n-1;i++){
        	for(int j=i+1;j<n;j++){
        		if(a[i][1]>a[j][1]){
        		tempA = a[i][0];
        		tempB = a[i][1];
        		a[i][0] = a[j][0];
        		a[i][1] = a[j][1];
        		a[j][0] = tempA;
        		a[j][1] = tempB;
        		}
        		else if(a[i][1]==a[j][1] && a[i][0]>a[j][0]){
        			tempA = a[i][0];
            		tempB = a[i][1];
            		a[i][0] = a[j][0];
            		a[i][1] = a[j][1];
            		a[j][0] = tempA;
            		a[j][1] = tempB;
        		}

        	}
        }
        int max = 0;
        int count = 1;
        while(count>0 && n>0){
        	count += a[n-1][1];
        	count--;
        	max += a[n-1][0];
        	n--;
        }
        System.out.println(max);

    }
}