#include<bits/stdc++.h>
#include <ext/pb_ds/assoc_container.hpp>
#include <ext/pb_ds/tree_policy.hpp>
#define FOR0(i,n) for(i=0;i<n;i++)
#define FOR(i,j,n) for(i=j;i<n;i++)
#define FORD(i,j,k) for(i=j;i>=k;i--)
#define pb push_back
#define mp make_pair
#define ff first
#define ss second
#define inf 1000000000
#define ninf -1000000000
#define endl '\n' 
#define she_told_me_dont_worry ios_base::sync_with_stdio (false) ; cin.tie(0) ; cout.tie(0) ;
#define ordered_set tree<int, null_type,less<int>, rb_tree_tag,tree_order_statistics_node_update>
// Use cout.flush() for interactive problems.
// Use this for increased stack size: g++ -o a.exe -Wl,--stack=256000000 -O2 source.cpp
inline long long  MAX2(long long  a, long long int b){return (a)>(b)?(a):(b);}
inline long long  MAX3(long long  a, long long  b,long long  c){return (a)>(b)?((a)>(c)?(a):(c)):((b)>(c)?(b):(c));}
inline long long  MIN2(long long  a, long long  b){return (a)<(b)?(a):(b);}
inline long long  MIN3(long long  a, long long b,long long c){return (a)<(b)?((a)<(c)?(a):(c)):((b)<(c)?(b):(c));}
using namespace std;
typedef long long ll;
typedef pair<int,int> ii;
typedef pair<ll, ll> pll;
typedef vector<int> vi;
typedef vector<ll> vll;
typedef vector< ii > vii;
typedef struct voter
{
    int m, p;
    voter(int a, int b)
    {
        m = a;
        p = b;
    }
} Voter;
bool compare(Voter lhs, Voter rhs)
{
    if(lhs.m == rhs.m)
        return lhs.p > rhs.p;
    return lhs.m < rhs.m;
}
int main()
{
    she_told_me_dont_worry
    int t;
    cin>>t;
    while(t--)
    {
        int n;
        cin>>n;
        int i;
        vector< Voter > voters;
        FOR0(i, n)
        {
            int m, p;
            cin>>m>>p;
            voters.pb(Voter(m, p));
        }
        sort(voters.begin(), voters.end(), compare);
        int a[n+5];
        a[0] = voters[0].m;
        int pos = 0;
        FOR(i, 1, n)
        {
            int req = voters[i].m - i;
            a[i] = MAX2(req, a[i-1]);
            if(a[i] != a[i-1]) pos = i;
        }
        ll ans = 0;
        int req = a[pos];
        vi values;
        FORD(i, n-1, pos+1)
            values.pb(voters[i].p);
        sort(values.begin(), values.end());
        int si = values.size();
        FOR0(i, si)
        {
            if(!req) break;
            ans += 1LL*values[i];
            req--;
        }
        cout<<ans<<endl;
    }
    cerr <<endl<< "Time elapsed : " << clock() * 1000.0 / CLOCKS_PER_SEC << " ms" << '\n';
}