#include <bits/stdc++.h>
using namespace std;
void Solve() {
  int t, n, pi, mi;
  cin >> t;
  while (t--) {
    cin >> n;
    map<int, vector<long long>> mdsp;
    multiset<long long> p;
    for (int i = 0; i < n; i++) {
      cin >> mi >> pi;
      mdsp[mi].push_back(pi);
    }
    long long ans = 0;
    int damua = 0, ctconlai = n;
    for (auto it = mdsp.rbegin(); it != mdsp.rend(); it++) {
      ctconlai += damua - (*it).second.size();
      p.insert((*it).second.begin(), (*it).second.end());
      if (ctconlai < (*it).first) {
        int muathem = (*it).first - ctconlai;
        damua += muathem;
        while (muathem > 0) {
          ans += *p.begin();
          p.erase(p.begin());
          muathem--;
        }
      }
    }
    cout << ans << '\n';
  }
}
int main() {
  ios_base::sync_with_stdio(0);
  cin.tie(0);
  Solve();
  return 0;
}
