import java.util.*;
import java.io.*;
import java.math.BigInteger;
 
public class Main
{
	static final int mod = (int)1e9+7;
	static int N = (int)2e6 + 2;
	static long[][] salary;
	public static void main(String[] args) throws Exception
	{
		FastReader in = new FastReader();
		PrintWriter out = new PrintWriter(System.out);
		int test = in.nextInt();
		while(test-- > 0)
		{
			int n = in.nextInt();
			long[][] arr = new long[n + 1][2];
			for(int i = 1; i <= n; i++)
			{
				arr[i][0] = in.nextInt();
				arr[i][1] = in.nextInt();
			}
			Arrays.sort(arr, 1, n + 1,(long[] a, long[] b) -> Long.compare(a[0], b[0]));
			long ans = 0, bought = 0;
			PriorityQueue<Long> pq = new PriorityQueue();
			for(int i = n; i > 0; i--)
			{
				pq.add(arr[i][1]);
				if(i - 1 + bought < arr[i][0])
				{
					ans += pq.poll();
					bought++;
				}
			}
			out.println(ans);
		}
		out.flush();
	}
}
 
class FastReader
{
	BufferedReader br;
	StringTokenizer st;
 
	public FastReader()
	{
	    br = new BufferedReader(new InputStreamReader(System.in));
	}
 
	public String next() throws IOException
	{
	    if(st == null || !st.hasMoreElements())
	    {
	        st = new StringTokenizer(br.readLine());
	    }

	    return st.nextToken();
	}
 
	public int nextInt() throws IOException
	{
	    return Integer.parseInt(next());
	}
 
	public long nextLong() throws IOException
	{
	    return Long.parseLong(next());
	}
 
	public String nextLine() throws IOException
	{
		return br.readLine();
	}
}