#include <bits/stdc++.h>
using namespace std;
const int MAX = 1000005;
const int INF = 1e9;
int n;
priority_queue<int> cola;
vector<pair<int, int> > v;
int main() {
  int t, m, p;
  cin >> t;
  while (t--) {
    cin >> n;
    for (int i = 0; i < int(n); ++i) {
      cin >> m >> p;
      v.push_back(make_pair(m, p));
    }
    sort((v).begin(), (v).end());
    int sol = 0;
    int cont = 0;
    for (int i = n - 1; i >= 0; i--) {
      cola.push(-v[i].second);
      if (v[i].first > i + cont) {
        sol += -cola.top();
        cola.pop();
        cont++;
      }
    }
    cout << sol << endl;
    v.clear();
    while (!cola.empty()) cola.pop();
  }
  return 0;
}
