#include <bits/stdc++.h>
using namespace std;
long long int cmp(pair<long long int, long long int> p1,
                  pair<long long int, long long int> p2) {
  if (p1.first != p2.first)
    return p1.first < p2.first;
  else
    return p1.second > p2.second;
}
void solve() {
  long long int n, k, ans = 0;
  cin >> n;
  long long int p[n], m[n];
  vector<pair<long long int, long long int> > v;
  long long int c = 0;
  long long int vis[n];
  memset(vis, 0, sizeof(vis));
  for (long long int i = 0; i < n; i++) {
    cin >> m[i] >> p[i];
    if (m[i] == 0) {
      c++;
      vis[i] = 1;
    } else
      v.push_back({p[i], m[i]});
  }
  vector<pair<long long int, long long int> > buy;
  while (c < n) {
    long long int f = 0;
    for (long long int i = 0; i < n; i++) {
      if (vis[i] == 0 && c >= v[i].second) {
        vis[i] = 0;
        c++;
        f = 1;
      }
    }
    if (f)
      continue;
    else {
      long long int minn = 1e9 + 10, maxx = 0, ind = -1;
      for (long long int i = 0; i < n; i++) {
        if (vis[i] == 0 && v[i].first < minn) {
          minn = v[i].first;
          maxx = v[i].second;
          ind = i;
        } else if (vis[i] == 0 && v[i].first == minn) {
          maxx = max(maxx, v[i].second);
          ind = i;
        }
      }
      long long int ind1 = -1, f = 0, maxx1 = -1;
      for (long long int i = 0; i < (long long int)buy.size(); i++) {
        if (buy[i].second <= c) {
          if (buy[i].first > maxx1) {
            maxx1 = buy[i].first;
            ind1 = i;
            f = 1;
          }
        }
      }
      if (f == 0) {
        buy.push_back({v[ind].first, v[ind].second});
        vis[ind] = 1;
        ans += v[ind].first;
        c++;
      } else {
        buy.push_back({v[ind].first, v[ind].second});
        vis[ind] = 1;
        ans += v[ind].first - buy[ind1].first;
        buy.erase(buy.begin() + ind1);
        c++;
      }
    }
  }
  cout << ans << "\n";
}
signed main() {
  ios_base::sync_with_stdio(0);
  cin.tie(0);
  cout.tie(0);
  long long int t;
  cin >> t;
  while (t--) {
    solve();
  }
}
