
import java.util.Arrays;
import java.util.Scanner;

import java.util.TreeSet;


public class balanced_tunnel {
	
	public static class pair_mi implements Comparable<pair_mi>
	{
		int m;
		int idx;
		pair_mi(int m,int idx)
		{
			this.m=m;
			this.idx=idx;
		}

		@Override
		public int compareTo(pair_mi o) {
			// TODO Auto-generated method stub
			return this.m-o.m;
		}
		
	}
	
	public static class pair_pi implements Comparable<pair_pi>
	{
		int p;
		int idx;
		pair_pi(int p,int idx)
		{
			this.p=p;
			this.idx=idx;
		}

		@Override
		public int compareTo(pair_pi o) {
			// TODO Auto-generated method stub
			return this.p-o.p;
		}
		
	}

	public static void main(String[] args) {
		
		Scanner s=new Scanner(System.in);
		int t=s.nextInt();
		
		for(int i=0;i<t;i++)
		{
			int p=s.nextInt();
			pair_mi[] mi=new pair_mi[p];
			pair_pi[] pi=new pair_pi[p];
			for(int k=0;k<p;k++)
			{
				int m=s.nextInt();
				int pp=s.nextInt();
				mi[k]=new pair_mi(m,k+1);
				pi[k]=new pair_pi(pp,k+1);
			}
			Arrays.sort(pi);
			Arrays.sort(mi);
			boolean[] vis=new boolean[p+1];
			int count=0;
			int cost=0;
			for(int k=0;k<mi.length;k++)
			{
				if(vis[mi[k].idx]==false)
				{
					if(count>=mi[k].m)
					{
						vis[mi[k].idx]=true;
						count++;
					}
					else 
					{
						int j=0;
						while(j<pi.length&&count!=mi[k].m)
						{
						
							if(vis[pi[j].idx]==false&&pi[j].idx!=mi[k].idx)
							{
								cost+=pi[j].p;
								vis[pi[j].idx]=true;
								count++;
								
							}
							j++;
						}
						}
						vis[mi[k].idx]=true;
						count++;
					}
				}
			System.out.println(cost);
			}
			
		}

	}



//aabbaaacaabbaa