import java.util.*;
import java.lang.*;
import java.io.*;
 
public class Main
{
	PrintWriter out = new PrintWriter(System.out);
	BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
    StringTokenizer tok = new StringTokenizer("");
    String next() throws IOException {
        if (!tok.hasMoreTokens()) { tok = new StringTokenizer(in.readLine()); }
        return tok.nextToken();
    }
    int ni() throws IOException { return Integer.parseInt(next()); }
    long nl() throws IOException { return Long.parseLong(next()); }
    
    static int mv= 1000000001;
    
    void solve() throws IOException {
        for (int TC=ni();TC>0;TC--) {
            int n=ni();
            int[][]A=new int[n][2];
            int[]C=new int[n];
            for (int x=0;x<n;x++) { A[x][0]=ni(); A[x][1]=ni(); }
            Arrays.sort(A,(a,b)->Integer.compare(a[0],b[0]));
            for (int x=0;x<n;x++) C[x]=A[x][1];
            
            long ans=0;
            PriorityQueue<Integer>PQ = new PriorityQueue();
            int c=0;
            int p=n-1;
            int q=n-1;
            while (p>0) {
                int r=0;
                while (q>=0 && A[q][0]==A[p][0]) { PQ.add(A[q][1]); q--; r++; }
                while (A[p][0]>q+1+c) { ans+=PQ.poll(); c++; }
                p=q;
            }
            out.println(ans);
        }
        out.flush();
    }
    
    public static void main(String[] args) throws IOException {
        new Main().solve();
    }
}