#include <bits/stdc++.h>
using namespace std;
void test_case() {
  int n;
  cin >> n;
  vector<pair<int, int> > vote(n + 1);
  priority_queue<int, vector<int>, greater<int> > q;
  for (int i = int(1); i < int(n + 1); i++) {
    int m, p;
    cin >> m >> p;
    vote[i] = {m, p};
  }
  sort(vote.begin(), vote.end());
  int curr = 0;
  long long res = 0;
  for (int i = n; i >= 0; i--) {
    q.push(vote[i].second);
    if (i - 1 + curr < vote[i].first) {
      res += (long long)q.top();
      q.pop();
      curr++;
    }
  }
  cout << res << endl;
}
int main() {
  ios_base::sync_with_stdio(false);
  cin.tie(NULL);
  cout.tie(NULL);
  int T;
  cin >> T;
  while (T--) {
    test_case();
  }
  return 0;
}
