#include <bits/stdc++.h>
using namespace std;
int main() {
  ios_base::sync_with_stdio(false);
  cin.tie(NULL);
  long long t;
  cin >> t;
  for (; t > 0; t--) {
    long long n;
    cin >> n;
    vector<pair<long long, long long>> voter(n);
    for (long long i = 0; i < n; i++) {
      long long m, p;
      cin >> m >> p;
      voter[i] = {m, p};
    }
    sort(voter.begin(), voter.end());
    long long ans = 0, sofar = 0;
    set<pair<long long, long long>> myset;
    for (long long i = n - 1; i >= 0; i--) {
      long long wantmore = voter[i].first - i - sofar;
      long long count = 0, tcost = 0;
      set<pair<long long, long long>> new_set;
      while (!myset.empty() && count < wantmore) {
        auto it = myset.begin();
        pair<long long, long long> ts = (*it);
        new_set.insert(ts);
        myset.erase(it);
        tcost += ts.first;
        count++;
      }
      if (count >= wantmore && tcost <= voter[i].second) {
        sofar += count;
        ans += tcost;
        myset.insert({voter[i].second, i});
      } else {
        sofar++;
        ans += voter[i].second;
        while (!new_set.empty()) {
          auto it = new_set.begin();
          pair<long long, long long> ts = (*it);
          new_set.erase(it);
          myset.insert(ts);
        }
      }
    }
    cout << ans << endl;
  }
  return 0;
}
