#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);
    }
    vector<tuple<long long, vector<long long>>> layers;
    vector<long long> had;
    long long curs = 0;
    for (map<long long, vector<long long>>::iterator pointer = voters.begin();
         pointer != voters.end(); pointer++) {
      layers.push_back(make_tuple(pointer->first, pointer->second));
      had.push_back(curs);
      curs += pointer->second.size();
    }
    long long bonus = 0;
    long long ans = 0;
    for (int i = layers.size() - 1; i >= 0; i--) {
      if (had[i] + bonus < get<0>(layers[i])) {
        sort(get<1>(layers[i]).begin(), get<1>(layers[i]).end());
        for (int j = 0;
             j < get<1>(layers[i]).size() && had[i] + bonus < get<0>(layers[i]);
             j++) {
          ans += get<1>(layers[i])[j];
          bonus++;
        }
      } else {
        if (i > 0) {
          for (int j = 0; j < get<1>(layers[i]).size(); j++) {
            get<1>(layers[i - 1]).push_back(get<1>(layers[i])[j]);
          }
        }
      }
    }
    cout << ans << endl;
  }
  return 0;
}
