#include <bits/stdc++.h>
#include <ext/pb_ds/assoc_container.hpp>
using namespace std;
using namespace __gnu_pbds;
 
#define int long long
#define ll long long
#define vi vector <int>
#define vii vector <pair<int,int> >
#define rep(i,a,b) for (int i=a;i<b;i++)
#define repD(i,a,b) for (int i=a;i>b;i--)
#define pb push_back
#define pii pair <int,int>
#define ff first
#define ss second
#define all(a) a.begin(),a.end()
#define MOD 1000000007
#define PI 3.14159265359
 
typedef tree<int,null_type,less<int>,rb_tree_tag, tree_order_statistics_node_update> ordered_set;
///*X.find_by_order("index")
///X.order_of_key("key")
 
#define deb(x) {x}
#ifndef local
	#define deb(x) ;
#endif
 
 
///----------------------------------------------------------------------------------

int n;
map <int, vi> price;
map <int, int> rem;

void solve()
{
	cin >> n;
	rem.clear();
	price.clear();
	
	int m, p;
	rep(i,0,n)
	{
		cin >> m >> p;
		price[m].pb(p);
	}
	
	multiset<pii> ok;
	int num = 0, cost = 0;
	for (auto &x:price)
	{
		sort(all(x.ss));
		reverse(all(x.ss));
		
		rep(i,0,min(n-x.ff, (int)x.ss.size()))
		{
			ok.insert({x.ss[i], -x.ff});
			rem[x.ff]++;
		}
		
		rep(i,min(n-x.ff, (int)x.ss.size()), (int)x.ss.size())
		{
			cost += x.ss[i];
			num ++;
		}
	}	
	
	for (auto x: rem)
	{
		if (num >= x.ff)
			num += x.ss;
		else
		{
			while(num < x.ff)
			{
				pii best = *ok.begin();
				ok.erase(ok.begin());
				best.ss = -best.ss;
				cost += best.ff;
				num ++;
				rem[best.ss]--;
			}
			num += rem[x.ff];
		}
	}
	cout << cost << "\n";
}
signed main()
{
	ios_base::sync_with_stdio(false);cin.tie(NULL);
 	
 	#ifdef local
	//freopen("input.txt","r",stdin);
	//freopen("output.txt","w",stdout);
	clock_t qwertyuiop = clock();
	#endif
 
	int t=1;
	cin>>t;	
	rep(a,0,t)
	{
		//cout<<"Case #"<<a+1<<": ";
		solve();
		#ifdef local
			cout << endl;
		#endif

	}
	
	#ifdef local
	{qwertyuiop = clock() - qwertyuiop;double time_taken = ((double)qwertyuiop)/CLOCKS_PER_SEC;cerr<<fixed<<setprecision(5)<<"\n\nTime Taken : "<<time_taken<<" seconds\n";}
	#endif
}