#include<bits/stdc++.h>
using namespace std;
#define  S second
long long int modInverse(long long int a,long long int m) 
{ 
    long long int m0 = m; 
    long long int y = 0, x = 1; 
  
    if (m == 1) 
      return 0; 
  
    while (a > 1) 
    { 
        // q is quotient 
        int q = a / m; 
        int t = m; 
  
        // m is remainder now, process same as 
        // Euclid's algo 
        m = a % m, a = t; 
        t = y; 
  
        // Update y and x 
        y = x - q * y; 
        x = t; 
    } 
  
    // Make x positive 
    if (x < 0) 
       x += m0; 
  
    return x; 
} 
int check(string s)
{
	int y=s.size();
	for(int i=1;i<=y; i++)
	{
		if(s[i%y]==s[(i+1)%y]||s[i%y]==s[(i-1)%y])
		{
			
		}
		else{
			return 0;
		}
	}
	return 1;
}
void solve()
{
	 int n;
	 cin>>n;
	 pair<int,int> A[n];
	 multiset<int > lol;
	 multiset<int  > :: iterator it;
	 for(int i=0;i<n; i++)
	 {
	 	int a,b;
	 	cin>>a>>b;
	 	
	 	A[i]={a,b};
	 }
	 sort(A,A+n);
	 
	 int curr=0;
	 long long int ans=0;
	 int visit[n]={0};
	 for(int i=0;i<n; i++)
	 {
	 	
	 	if(A[i].first<=curr)
	 	{
	 		curr++;
		 }
		 else{
		 	int u=A[i].first-curr;
		 	visit[i]=u;
		 	
		 	while(u--){
		 	curr++;
		 }
		 	//curr++;
		 }
		 
	 }
	 int pot=0;
	 for(int i=n-1;i>=0; i--)
	 {
	 	lol.insert(A[i].second);
	 	//cout<<visit[i]<<" ";
	 	int g=visit[i]-pot;
	 	for(int j=0;j<g; j++)
	 	{
	 		pot++;
	 		it=lol.begin();
	 		ans+=*it;
	 		lol.erase(it);
		 }
	 }
	 cout<<ans<<"\n";
}
int main()
{
	ios_base::sync_with_stdio(false);
    cin.tie(NULL);
	int t=1;
	cin>>t;
	while(t--)
	{
		solve();
	}
}