#include <bits/stdc++.h>
using namespace std;
using ll = long long;
using ld = long double;
int main() {
  ll t;
  cin >> t;
  while (t--) {
    map<ll, vector<ll>> ma;
    ll n, st = 0;
    cin >> n;
    for (ll i = 0; i < n; i++) {
      ll a, b;
      cin >> a >> b;
      ma[a].push_back(b);
    }
    vector<vector<ll>> vov;
    vector<ll> v, mv;
    mv.push_back(ma.begin()->first);
    for (auto x : ma) {
      if (st < x.first && v.size()) {
        sort(v.begin(), v.end(), greater<ll>());
        vov.push_back(v);
        v.clear();
        mv.push_back(x.first);
      }
      st += x.second.size();
      for (ll xx : x.second) {
        v.push_back(xx);
      }
    }
    sort(v.begin(), v.end(), greater<ll>());
    vov.push_back(v);
    assert(mv.size() == vov.size());
    ll cur = 0, co = 0, fl = 0, en = max(0LL, (ll)vov.size() - 1);
    if (ma.find(0) != ma.end()) {
      cur = vov[0].size();
      fl = 1;
    }
    while (fl <= en) {
      cur++;
      co += vov[en].back();
      vov[en].pop_back();
      if (vov[en].size() == 0) {
        en--;
      }
      while (fl <= en && cur >= mv[fl]) {
        cur += vov[fl].size();
        fl++;
      }
    }
    cout << co << "\n";
  }
}
