/*
 ID: tommatt1
 LANG: JAVA
 TASK: 
*/
import java.util.*;
import java.io.*;
public class cf1251e2{

	public static void main(String[] args)throws IOException {
		PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(System.out)));
		BufferedReader bf=new BufferedReader(new InputStreamReader(System.in));
		StringTokenizer st=new StringTokenizer(bf.readLine());
		int tt=Integer.parseInt(st.nextToken());
		while(tt-->0) {
			st=new StringTokenizer(bf.readLine());
			int n=Integer.parseInt(st.nextToken());
			pair[] a=new pair[n];
			for(int i=0;i<n;i++) {
				st=new StringTokenizer(bf.readLine());
				int a1=Integer.parseInt(st.nextToken());
				int a2=Integer.parseInt(st.nextToken());
				a[i]=new pair(a1,a2);
			}
			Arrays.sort(a);
			int x=n-1;
			int z=n-1;
			int inc=0;
			PriorityQueue<Integer> q=new PriorityQueue<>();
			long ans=0;
			while(x>0) {
				while(z>=0&&a[z].a==a[x].a) {
					q.add(a[z].b);
					z--;
				}
				while(a[x].a>z+1+inc) {
					ans+=q.poll();
					inc++;
				}
				x=z;
			}
			out.println(ans);
		}
		out.close();
	}
	static class pair implements Comparable<pair>{
		int a;int b;
		public pair(int x,int y) {
			a=x;b=y;
		}
		public int compareTo(pair p) {
			return a-p.a;
			//if(a>p.a) return 1;
		}
	}
}
