#include<bits/stdc++.h>
#include<ext/pb_ds/assoc_container.hpp>
#define int long long
#define pb push_back
#define pii pair<int,int>
#define x first
#define y second
#define sz(x) (int)x.size()
using namespace std;

void solve() {
    int n;
    cin >> n;
    vector<pii>a(n);
    vector<vector<int>> pr(n);
    for (int i = 0; i < n; ++i) {
        cin >> a[i].x >> a[i].y;
    }
    sort(a.begin(), a.end());
    int cnt = 0;
    multiset <int> bt;
    for (int i = 0; i < n; ++i) {
        for (auto c : pr[i])
            bt.insert(c);
        if (a[i].x <= i) {
            if (sz(bt) && cnt + a[i].y - *(--bt.end()) < cnt) {
                cnt += a[i].y;
                cnt -= (*--bt.end());
                bt.erase(--bt.end());
                pr[a[i].x].pb(a[i].y);
            }
        } else {
            if (sz(bt)) {
                cnt += a[i].y;
                cnt -= (*--bt.end());
                bt.erase(--bt.end());
                pr[a[i].x].pb(a[i].y);
            } else {
                cnt += a[i].y;
                pr[a[i].x].pb(a[i].y);
            }
        }
    }
    cout << cnt << endl;
}

signed main() {
    ios::sync_with_stdio(0);
    cin.tie(0);
    cout.tie(0);
    int t;
    cin >> t;
    while (t--) {
        solve();
    }
    return 0;
}
