/*input
3
3
1 5
2 10
2 8
7
0 1
3 1
1 1
6 1
1 1
4 1
4 1
6
2 6
2 3
2 8
2 7
4 4
5 5
*/
#include<bits/stdc++.h>
#define int long long
#define MOD 1000000007
#define MAX 100005
#define pb push_back
#define mp make_pair
#define pii pair<int,int>
#define ppi pair<pii,int>
#define mii map<int,int>
#define vi vector<int>
#define ff first
#define ss second
#define T int t;cin>>t;while(t--)
#define loop(i,a,b) for(int i=a;i<b;i++)
#define umi unordered_map<int,int>
#define maxheap priority_queue<int>
#define minheap priority_queue<int,vector<int>,greater<int> >
#define inp(n) for(int i=0;i<n;i++)
#define N 2000005

using namespace std;
using namespace std::chrono;

vector<pii>v;
bool comp(pii &a,pii &b){
	return (a.ff < b.ff) || (a.ff == b.ff && a.ss < b.ss);
}

struct point{
	int m,p,index;
	point(int m,int p,int index){
		this->m = m;this->p = p;this->index = index;
	}
};

bool comp2(point &a,point &b){
	return (a.p < b.p) || (a.p == b.p && a.m > b.m);
}

int evaluate(int n,int done,vector<pii>&v){
	int ans = 0;
	for(int i = 0; i < n; ++i)
	{
		if(done < v[i].ff){
			ans += v[i].ff-done;
			done = v[i].ff;
		}
		done++;
	}
	return ans;
}

bool possible(int idx,int pay,int n){
	vector<point>vec;
	for(int i = idx; i < n; i++){
		point p(v[i].ff,v[i].ss,i);
		vec.pb(p);
	}
	sort(vec.begin(),vec.end(),comp2);

	bool mark[n]={};
	for(int i = 0; i < pay; ++i)
	{
		mark[vec[i].index] = true;
	}
	vector<pii> temp;

	for(int i = 0; i < n; ++i)
	{
		if(mark[i] == false)
			temp.pb(v[i]);
	}
	int done = pay;

	if(evaluate(n-pay,done,temp) == 0)
		return true;

	return false;
}

int bsearch(int low,int high,int pay,int n){
	if(low>high)
		return low;
	int mid = (low+high)/2;
	if(possible(mid,pay,n))
		return bsearch(low,mid-1,pay,n);
	return bsearch(mid+1,high,pay,n);
}

signed main(){
	auto start = high_resolution_clock::now();
	// your code here
T{
	int n,x,y;
	cin >> n;
	v.clear();
	loop(i,0,n){
		cin >> x >> y;
		v.pb(mp(x,y));
	}
	sort(v.begin(), v.end(), comp);
	
	int pay = evaluate(n,0,v);
	int idx = bsearch(0,n-pay-1,pay,n);
	int res = 0;
	vi vv;
	for (int i = idx; i < n; ++i)
	{
		vv.pb(v[i].ss);
	}
	sort(vv.begin(), vv.end());
	for (int i = 0; i < min(pay,n); ++i)	res += vv[i];

	cout << res << "\n";
}




auto stop = high_resolution_clock::now();
auto duration = duration_cast<microseconds>(stop-start);
//cout<<"\n"<<duration.count()<<" microseconds\n";
}
