
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.PriorityQueue;
import java.util.Scanner;

public class qweqwe {
	static pair ar[];
	
	public static void main(String args[]) {
		Scanner scan=new Scanner(System.in);
		int t=scan.nextInt();
		for(int q=0;q<t;q++) {
				int n=scan.nextInt();
				int m[]=new int[n];
				int p[]=new int[n];
				ar=new pair[n];
				for(int i=0;i<n;i++) {
					ar[i]=new pair(scan.nextInt(),scan.nextInt());
				}
				Arrays.parallelSort(ar,new compare());
				int cnt=0;
				long sum=0;
				PriorityQueue<Integer> pq=new PriorityQueue<Integer>();
				for(int i=n-1;i>=0;i--) {
//					pq.add(0);
					int x=ar[i].p;
					pq.add(x);
					int pre=i;
					if(pre+cnt>=ar[i].m) {
						continue;
					}
					sum+=pq.poll();
					cnt++;
				}
				System.out.println(sum);
				
		}
	}
}class pair{
	int m;
	int p;
	pair(int x,int y){
		m=x;
		p=y;
	}

}
class compare implements Comparator<pair>{

	@Override
	public int compare(pair o1, pair o2) {
		if(o1.m>o2.m) {
			return 1;
		}else if(o1.m<o2.m) {
			return -1;
		}else {
			if(o1.p>o2.p) {
				return 1;
			}else if(o1.p<o2.p) {
				return -1;
			}else {
				return 0;
			}
		}
	}
	
}
