#include<bits/stdc++.h>
#define pb push_back
#define mp make_pair
#define fastread ios_base::sync_with_stdio(false); cin.tie(NULL); cout.tie(NULL);
#define openfile ifstream cin; ofstream cout; cin.open("input.txt"); cout.open("output.txt");
#define f(i, x, y) for(int i = x; i < y; i++)
#define all(X) X.begin(), X.end()
#define int long long
// # define int unsigned int
#define ll long long
#define key pair<int, int>
#define keyy pair<pair<int, int>, int>
#define keyyy pair<pair<int, int>, pair<int, int>>
#define keyd pair<double, double>
#define ff first
#define ss second
#define double long double
int mod = 1e9+7;
// int mod = 998244353;
const int inf = 1e18;
using namespace std;

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

main()
{
    fastread;
    int T; cin>>T;
    while(T--)
    {
        int n; cin>>n; key a[n+1]; f(i, 1, n+1) cin>>a[i].ff>>a[i].ss;
        sort(a+1, a+n+1, comp);
        int ans = 0, c = 0;
        set<int> s;
        for(int i = n; i > 0; i--)
        {
            while(c + i - 1 < a[i].ff)
            {
                int x = *(s.begin()); s.erase(s.begin());
                ans += x; c++;
            }
            s.insert(a[i].ss);
        }
        cout<<ans<<"\n";
    }
}