import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.IOException;
import java.util.*;
import java.lang.Math;
 
public class Solution {
	static BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
	static StringTokenizer st;
	static long mod = 998244353;
    
	public static void main(String[] args) throws IOException {
	    Solution sol = new Solution();
  	    st = new StringTokenizer(br.readLine());
  		int q = Integer.parseInt(st.nextToken());
  		for(int i = 0; i<q; i++){
	        sol.solve();
  		}
	}
	
	private void solve() throws IOException {
	    // Read inputs
	    st = new StringTokenizer(br.readLine());
 		int n = Integer.parseInt(st.nextToken());
        
        int[][] a = new int[n][2];
        
        for(int i = 0; i<n; i++) {
	        st = new StringTokenizer(br.readLine());
            a[i][0] = Integer.parseInt(st.nextToken()); // m
            a[i][1] = Integer.parseInt(st.nextToken()); // p
        }
        
        long out = 0;
        Arrays.sort(a, (int[] b, int[] c) -> b[0]-c[0]); // sort by m in asc
        int count = 0;
        PriorityQueue<Integer> pq = new PriorityQueue();
        for(int i = n-1; i>=0; i--) {
            pq.add(a[i][1]);
            if(a[i][0] -count > i) {
                out += pq.poll();
                count++;
            }
        }
        
        System.out.println(out);
	}
}