import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.PriorityQueue;
import java.util.StringTokenizer;

public class E {
	public static void main(String[] args) {
		FS in = new FS();
		PrintWriter out = new PrintWriter(System.out);
		
		int T = in.nextInt();
		for(int runs = 1; runs <= T; runs++) {
			int N = in.nextInt();
			P ar[] = new P[N];
			for(int i = 0; i < N; i++)
				ar[i] = new P(in.nextLong(), in.nextLong());
			Arrays.sort(ar);
			int r = N-1;
			int l = N-1;
			int taken = 0;
			long res = 0;
			PriorityQueue<Long> pq = new PriorityQueue<Long>();
			while(r >= 0) {
				while(l >= 0 && ar[l].m == ar[r].m) pq.add(ar[l--].p);
				while(taken < ar[r].m - (l+1)) { taken++; res += pq.poll();}
				r = l;
			}
			out.println(res);
		}
		out.close();
	}
	
	static class P implements Comparable<P>{
		long p,m;
		public P(long mm, long pp) {
			p=pp;
			m=mm;
		}
		@Override
		public int compareTo(P o) {
			return Long.compare(m, o.m);
		}
	}

	static class FS{
		BufferedReader br;
		StringTokenizer st;
		public FS() {
			br = new BufferedReader(new InputStreamReader(System.in));
		}
		String next() {
			while(st == null || !st.hasMoreElements()) {
				try { st = new StringTokenizer(br.readLine());}
				catch(Exception e) { throw null;}
			}
			return st.nextToken();
		}
		int nextInt() {return Integer.parseInt(next());}
		long nextLong() {return Long.parseLong(next());}
		double nextDouble() {return Double.parseDouble(next());}
	}
	
	static void sort(int a[]) {
		ArrayList<Integer> list = new ArrayList<Integer>();
		for(int ii : a) list.add(ii);
		Collections.sort(list);
		for(int i = 0; i < a.length; i++) a[i] = list.get(i);
	}
}
