//raja1999

//#pragma comment(linker, "/stack:200000000")
//#pragma GCC optimize("Ofast")
//#pragma GCC target("sse,sse2,sse3,ssse3,sse4,avx,avx2")

#include <bits/stdc++.h>
#include <vector>
#include <set>
#include <map>
#include <string> 
#include <cstdio>
#include <cstdlib>
#include <climits>
#include <utility>
#include <algorithm>
#include <cmath>
#include <queue>
#include <stack>
#include <iomanip> 
#include <ext/pb_ds/assoc_container.hpp>
#include <ext/pb_ds/tree_policy.hpp> 
//setbase - cout << setbase (16)a; cout << 100 << endl; Prints 64
//setfill -   cout << setfill ('x') << setw (5); cout << 77 <<endl;prints xxx77
//setprecision - cout << setprecision (14) << f << endl; Prints x.xxxx
//cout.precision(x)  cout<<fixed<<val;  // prints x digits after decimal in val

using namespace std;
using namespace __gnu_pbds;
#define f(i,a,b) for(i=a;i<b;i++)
#define rep(i,n) f(i,0,n)
#define fd(i,a,b) for(i=a;i>=b;i--)
#define pb push_back
#define mp make_pair
#define vi vector< int >
#define vl vector< ll >
#define ss second
#define ff first
#define ll long long
#define pii pair< int,int >
#define pll pair< ll,ll >
#define sz(a) a.size()
#define inf (1000*1000*1000+5)
#define all(a) a.begin(),a.end()
#define tri pair<int,pii>
#define vii vector<pii>
#define vll vector<pll>
#define viii vector<tri>
#define mod (1000*1000*1000+7)
#define pqueue priority_queue< int >
#define pdqueue priority_queue< int,vi ,greater< int > >
#define int ll

typedef tree<
int,
null_type,
less<int>,
rb_tree_tag,
tree_order_statistics_node_update>
ordered_set;

//std::ios::sync_with_stdio(false);
int vis[5005][5005];
int dp[5005][5005];
int iinf=inf,iter=0;
vector<vi>v(5005);
int previ[5005];
int compute(int pos,int cnt){
	if(pos==-1){
		return 0;
	}
	if(vis[pos][cnt]==iter){
		return dp[pos][cnt];
	}
	vis[pos][cnt]=iter;
	int val,p,res,i;
	val=previ[pos];
	val+=cnt;
	val=max(0LL,pos-val);
	p=0;
	f(i,0,val){
		p+=v[pos][i];
	}
	res=iinf;
	res=min(res,p+compute(pos-1,cnt+val));
	f(i,val,v[pos].size()){
		p+=v[pos][i];
		res=min(res,p+compute(pos-1,cnt+val+(val-i+1)));
	}
	return dp[pos][cnt]=res;
}
main(){
	std::ios::sync_with_stdio(false); cin.tie(NULL);
	int t,t1;
	cin>>t;
	//t=1;
	t1=t;
	iinf*=inf;
	while(t--){
		int n,m,p,prev,i;
		cin>>n;
		iter++;
		rep(i,n){
			v[i].clear();
		}
		rep(i,n){
			cin>>m>>p;
			v[m].pb(p);
		}
		rep(i,n){
			sort(all(v[i]));
		}
		prev=0;
		rep(i,n){
			previ[i]=prev;
			prev+=v[i].size();
		}
		cout<<compute(n-1,0)<<endl;
	}
	return 0;
} 
	