#include <bits/stdc++.h>
using namespace std;
const long long int mod = 1e9 + 7;
const long double eps = 1e-9;
void solve() {
  long long int n;
  cin >> n;
  priority_queue<pair<int, int>, vector<pair<int, int> >,
                 greater<pair<int, int> > >
      pq;
  long long int a, b;
  for (long long int i = 0; i < (long long int)(n); ++i) {
    cin >> a >> b;
    pq.push({b, a});
  }
  long long int m = 0, cost = 0;
  while (!pq.empty()) {
    priority_queue<pair<int, int>, vector<pair<int, int> >,
                   greater<pair<int, int> > >
        temp;
    m++;
    cost += pq.top().first;
    while (!pq.empty()) {
      long long int vote = pq.top().first;
      long long int men = pq.top().second;
      if (men < m) {
        m++;
      } else
        temp.push({vote, men});
      pq.pop();
    }
    pq = temp;
  }
  cout << cost << "\n";
  return;
}
signed main() {
  ios_base::sync_with_stdio(0);
  cin.tie(0);
  cout.tie(0);
  long long int t = 1;
  cin >> t;
  while (t--) solve();
  fflush(stdout);
  return 0;
}
