#include <bits/stdc++.h>

using namespace std;

int main()
{
    ios_base::sync_with_stdio(false);
    cin.tie(NULL);
    long long t,n,x,z,now,ans;
    cin>>t;
    for(long i=0;i<t;i++){
    cin>>n;
    ans=0;
    bool vis[n]={};
    map<long,long>m;
    map<long,vector<long long> >cnt;
    vector<long long>transformers,to_choose;
    pair<long,long long> arr[n];
    for(long j=0;j<n;j++){
    cin>>x>>z;
    arr[j]=make_pair(x,z);
    cnt[x].push_back(z);
    now=x;
    if(cnt[x].size()==2){
    transformers.push_back(x);
    }
    while(m[now]==1&&now<n){
    now++;
    }
    m[now]++;
    }
    for(long j=0;j<transformers.size();j++){
    z=transformers[j];
    vis[z]=true;
    for(long k=0;k<cnt[z].size();k++){
    to_choose.push_back(cnt[z][k]);
    }
    }
    sort(arr,arr+n,greater<pair<long,long long> >());
    for(long j=0;j<m[n];j++){
    if(!vis[arr[j].first]){
    to_choose.push_back(arr[j].second);
    }
    }
    sort(to_choose.begin(),to_choose.end());
    for(long j=0;j<m[n];j++){
    ans+=to_choose[j];
    }
    cout<<ans<<endl;
    }
    return 0;
}
