#include <bits/stdc++.h>

using namespace std;

#define ll long long int
#define pll pair<ll, ll>

int main() {
    ios_base::sync_with_stdio(false);
    cin.tie(NULL);
    cout.tie(NULL);

    int t;
    cin >> t;
    while (t--) {
        int n;
        cin >> n;
        vector<pll> v(n);
        for (int i = 0; i < n; i++) {
            cin >> v[i].first >> v[i].second;
        }
        sort(v.begin(), v.end(), [=] (auto& l, auto& r) {
            return l.first == r.first ? l.second < r.second : l.first < r.first;
        });

        int bought = 0;
        ll price = 0;
        map<int, int>  s;
        for (int j = n-1; j >= 0; j--) {
            s[v[j].second] += 1;
            if (v[j].first > j + bought) {
                bought += 1;
                int x = s.begin()->first;
                s[x] -= 1;
                price += x;
            }
        }
        cout << price << "\n";
    }




    return 0;
}

/*
     int t;
    cin >> t;
    while (t--) {
        int n;
        ll s;
        cin >> n >> s;
        vector<pll> v(n);
        int mid = (n+1) / 2;
        ll rest = s;
        for (int i = 0; i < n; i++) {
            cin >> v[i].first >> v[i].second;
            rest -= v[i].first;
        }
        sort(v.begin(), v.end(), [=] (auto& l, auto& r) {
            return l.first == r.first ? l.second < r.second : l.first < r.first;
        });
    }

 */