/* please give me your code, please -you */

#include <bits/stdc++.h>
#include <ext/pb_ds/assoc_container.hpp>
#include <ext/pb_ds/tree_policy.hpp>

using namespace std;
using namespace __gnu_pbds;

#define F first
#define S second
#define endl "\n"
#define pb push_back
#define mp make_pair
typedef long long ll;
typedef unsigned long long ull;
typedef long double ldob;
typedef double dob;
typedef pair<int, int> pii;
typedef pair<ll, ll> pll;
typedef tree<pii, null_type, less<pii>, rb_tree_tag, tree_order_statistics_node_update> ordered_set;


template <class T> ostream& operator << (ostream &os, const vector<T> &v) { for (T i : v) os << i << ' '; return os; }
template <class T> ostream& operator << (ostream &os, const set<T> &v) { for (T i : v) os << i << ' '; return os; }
template <class T, class S> ostream& operator << (ostream &os, const pair<T, S> &v) { os << v.F << ' ' << v.S; return os; }
template <class T, class S> ostream& operator << (ostream &os, const unordered_map<T, S> &v) { for (auto i : v) os << '(' << i.F << "=>" << i.S << ')' << ' '; return os; } 
template <class T, class S> ostream& operator << (ostream &os, const map<T, S> &v) { for (auto i : v) os << '(' << i.F << " => " << i.S << ')' << ' '; return os; } 
 
void fast()
{
    ios_base::sync_with_stdio(false);
    cin.tie(NULL);
    cout.tie(NULL);
    #ifndef ONLINE_JUDGE
        // freopen("input.txt", "r", stdin);
        // freopen("output.txt", "w", stdout);
	#endif
}

vector<vector<ll>> v;

void solve()
{
    int n; cin>>n;
    v.clear();
    v.resize(n+1);
    for(int i=0;i<n;i++)
    {
        ll a, p; cin>>a>>p;
        v[a].pb(p);
    }

    set<pll> s;
    ll cost = 0;
    int rem = n;
    int have = 0;
    for(int i=n-1;i>=0;i--)
    {
        if(v[i].empty()) continue;

        int req = i - (rem - v[i].size());
        for(int j=0;j<v[i].size();j++) s.insert({v[i][j], ll(j)});
        while(have < req)
        {
            cost += s.begin()->F;
            s.erase(s.begin());
            have++;
        }
        rem -= v[i].size();
    }
    cout<<cost<<endl;

}

int main()
{
    fast();
    int t;
    cin>>t;
    while(t--)
    solve();
}