#include <bits/stdc++.h>
using namespace std;
void solve() {
  int n;
  cin >> n;
  vector<int> p(n), m(n);
  for (int i = 0; i < n; ++i) {
    cin >> m[i] >> p[i];
  }
  vector<int> id(n);
  iota(id.begin(), id.end(), 0);
  sort(id.begin(), id.end(), [&](int i, int j) {
    return m[i] < m[j] or (m[i] == m[j] and p[i] < p[j]);
  });
  int cur = 0;
  long long ans = 0;
  vector<long long> tot(n + 10);
  for (int i = 0; i < n; ++i) {
    int v = id[i];
    if (m[v] <= cur) {
      ++cur;
      if (tot[1] > p[v]) {
        ans -= tot[1];
        ans += p[v];
        for (int j = 1; j < n + 9; ++j) {
          tot[j] = tot[j + 1];
        }
      }
      continue;
    }
    ans += p[v];
    ans -= tot[1];
    for (int j = 1; j < n + 9; ++j) {
      tot[j] = tot[j + 1];
    }
    tot[m[v] - cur] += p[v];
    ++cur;
  }
  cout << ans;
}
int main() {
  ios::sync_with_stdio(0);
  cin.tie(0), cout.tie(0);
  int t;
  cin >> t;
  while (t--) {
    solve();
    cout << '\n';
  }
  return 0;
}
