/* Code by detestmaths*/


import java.io.*;
import java.util.*;
import static java.lang.Math.*;
import static java.util.Arrays.*;

public class Main {
    public static void main(String[] args) throws IOException {
//        FastScanner in = new FastScanner("umbrella.in");
//        PrintWriter out = new PrintWriter("umbrella.out");
        FastScanner in = new FastScanner(System.in);
        PrintWriter out = new PrintWriter(System.out);
        int t = in.nextInt();
        while (t-- > 0) {
          int n = in.nextInt();
          pair p[] = new pair[n];
            for (int i = 0; i < n; i++) {
                p[i] = new pair(in.nextInt(),in.nextInt());
            }
            sort(p,new pair_comparator());
            int taken = 0;
            long s = 0;
            PriorityQueue<Long>q = new PriorityQueue<>();
            int id = n;
            while (id-- > 0){
                long cst = p[id].p;
                q.add(cst);
                if(id + taken >= p[id].m){
                    continue;
                }
                s+=q.poll();
                taken++;
            }
            out.println(s);
        }
        out.close();
    }
}
class pair{
    int m;
    long p;

    public pair(int m, long n) {
        this.m = m;
        this.p = n;
    }
}
class pair_comparator implements Comparator<pair>{

    @Override
    public int compare(pair pair, pair t1) {
        if(pair.m != t1.m)return Integer.compare(pair.m,t1.m);
        return Long.compare(pair.p,t1.p);
    }
}
class FastScanner {
    BufferedReader br;
    StringTokenizer st = new StringTokenizer("");

    public FastScanner(InputStream s) {
        br = new BufferedReader(new InputStreamReader(s));
    }

    public FastScanner(String s) throws FileNotFoundException {
        br = new BufferedReader(new FileReader(new File(s)));
    }

    public String next() throws IOException {
        if (!st.hasMoreTokens())
            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 double nextDouble() throws IOException {
        return Double.parseDouble(next());
    }
}