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

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

	FastReader in = new FastReader();
	PrintWriter out = new PrintWriter(System.out);
	void run(){
		int t=in.nextInt();
		for(int i=0;i<t;i++) {
			work();
		}
		out.flush();
	}
	long mod=1000000007;
	long gcd(long a,long b) {
		return b==0?a:gcd(b,a%b);
	}
	void work() {
		int n=in.nextInt();
		ArrayList<Integer>[] A=(ArrayList<Integer>[])new ArrayList[n];
		int[][] B=new int[n][];
		for(int i=0;i<n;i++) {
			A[i]=new ArrayList<>();
		}
		long ret=0;
		for(int i=0;i<n;i++) {
			int m=in.nextInt();
			int p=in.nextInt();
			B[i]=new int[] {m,p};
			A[m].add(p);
		}
		int pre=0;
		int[] sum=new int[n];
		for(int i=0;i<n;i++) {
			sum[i]=(i==0?0:sum[i-1])+A[i].size();
		}
		PriorityQueue<Integer> pq=new PriorityQueue<>();
		for(int i=n-1;i>=0;i--) {
			if(sum[i]+pre>=i+1) {
				for(int a:A[i]) {
					pq.add(a);
				}
			}else {
				try {
					while(sum[i]+pre<i+1) {
						ret+=pq.poll();
						pre++;
					}
				} catch (Exception e) {
					System.out.println(n);
					for(int[] b:B) {
						System.out.println(b[0]+".."+b[1]);
					}
				}
				
			}
		}
		out.println(ret);
	}
}



class FastReader
{
	BufferedReader br;
	StringTokenizer st;

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

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

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

	public long nextLong()
	{
		return Long.parseLong(next());
	}
}