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

	public static void main(String[] args) throws Exception{
		int num = 998244353;

		// TODO Auto-generated method stub
 		BufferedReader bf = new BufferedReader(new InputStreamReader(System.in));
 		PrintWriter out = new PrintWriter(System.out);
 		int t = Integer.parseInt(bf.readLine());
 		for(int i = 0;i<t;i++){
//	 		String input1 = bf.readLine().trim();
//	 		String input2 = bf.readLine().trim();
	 		int n = Integer.parseInt(bf.readLine());
	 		ArrayList<Voter> array = new ArrayList<>();
	 		long sum = 0;
	 		for(int j = 0;j<n;j++){
	 			StringTokenizer st = new StringTokenizer(bf.readLine());
	 			int m = Integer.parseInt(st.nextToken());
	 			int p = Integer.parseInt(st.nextToken());
	 			if (m >=n)
	 				sum+=p;
	 			else
	 				array.add(new Voter(m, p));
	 		}
	 		Collections.sort(array);
	 		int[] cost = new int[n];
	 		int[] numlater = new int[n];
	 		for(int j = 0;j<n;j++){
	 			cost[j] = array.get(j).getP();
	 			numlater[j] = Math.max(0,array.get(j).getM() - j);
	 		}
	 		PriorityQueue<Integer> p = new PriorityQueue<>();
	 		int currmax = 0;
	 		for(int j = n-1;j>=0;j--){
	 			p.add(array.get(j).getP());
	 			if (numlater[j] > currmax){
	 				for(int k = 0;k<numlater[j] - currmax;k++){
	 					sum+=p.remove();
	 				}
	 				currmax = numlater[j];
	 			}
	 		}
	 		out.println(sum);
	 		
 		}
 		
 		
 		out.println();
	 		
 		out.close();
 		
 		
 		
 	}
	static class Voter implements Comparable<Voter>{
		private int m;
		private int p;
		public Voter(int m, int p){
			this.m = m;
			this.p = p;
		}
		public int getM() {
			return m;
		}
		public void setM(int m) {
			this.m = m;
		}
		public int getP() {
			return p;
		}
		public void setP(int p) {
			this.p = p;
		}
		public int compareTo(Voter other){
			if (m != other.m)
				return m - other.m;
			else
				return p - other.p;
		}
		
	}
}
 	
 
//StringJoiner sj = new StringJoiner(" "); 
//sj.add(strings)
//sj.toString() gives string of those stuff w spaces or whatever that sequence is

 		
 		
 		
 		
	


