#include <bits/stdc++.h>
using namespace std;
int main() {
  ios_base::sync_with_stdio(true);
  cin.tie(NULL);
  long long T;
  cin >> T;
  while (T--) {
    long long V;
    cin >> V;
    map<long long, vector<long long>> voters;
    for (long long i = 0; i < V; i++) {
      long long mi, pi;
      cin >> mi >> pi;
      voters[mi].push_back(pi);
    }
    long long curs = 0;
    vector<map<long long, vector<long long>>::iterator> layers;
    vector<long long> had;
    map<long long, vector<long long>>::iterator last_pointer;
    for (map<long long, vector<long long>>::iterator pt = voters.begin();
         pt != voters.end(); pt++) {
      if (pt->first > curs || layers.size() == 0) {
        layers.push_back(pt);
        had.push_back(curs);
        last_pointer = pt;
      } else {
        for (long long i = 0; i < pt->second.size(); i++) {
          last_pointer->second.push_back(pt->second[i]);
        }
      }
      curs += pt->second.size();
    }
    long long bonus = 0;
    long long ans = 0;
    for (long long i = layers.size() - 1; i >= 0; i--) {
      if (layers[i]->first <= had[i] + bonus) {
        if (i > 0) {
          for (int j = 0; j < layers[i]->second.size(); j++) {
            layers[i - 1]->second.push_back(layers[i]->second[j]);
          }
        }
      } else {
        sort(layers[i]->second.begin(), layers[i]->second.end());
        long long ct = 0;
        while (layers[i]->first > had[i] + bonus &&
               ct <= layers[i]->second.size()) {
          ans += layers[i]->second[ct];
          ct++;
          bonus++;
        }
      }
    }
    cout << ans << endl;
  }
  return 0;
}
