#include <bits/stdc++.h>
using namespace std;
bool comp(pair<long long int, long long int> a,
          pair<long long int, long long int> b) {
  if (b.second == a.second)
    return b.first > a.first;
  else
    return b.second > a.second;
}
int main() {
  ios_base::sync_with_stdio(false);
  cin.tie(0);
  cout.tie(0);
  int t;
  cin >> t;
  while (t--) {
    int n;
    cin >> n;
    vector<pair<long long int, long long int> > p(n);
    vector<bool> bought(n, false);
    for (int i = 0; i < n; i++) cin >> p[i].first >> p[i].second;
    sort(p.begin(), p.end());
    int cnt = 0, i = 0;
    long long int cost = 0;
    while (cnt < n - 1) {
      if (p[i].first <= cnt && bought[i] == false) {
        cnt++;
        bought[i] = true;
        i++;
        continue;
      } else {
        int buy = p[i].first - cnt;
        sort(p.begin() + i, p.end(), comp);
        int j;
        if (cost > 0) cost = 0;
        for (j = i; j < i + buy; j++) {
          bought[i] = true;
          cost += p[j].second;
          cnt++;
        }
        i = j;
        sort(p.begin() + i, p.end());
      }
    }
    cout << cost << "\n";
  }
  return 0;
}
