#include <bits/stdc++.h>
using namespace std;
const int maxn = 5000;
int n;
int m[maxn + 1], p[maxn + 1];
int cnt[maxn + 1];
vector<int> V[maxn + 1];
int res;
int bought;
priority_queue<int, vector<int>, greater<int> > H;
void solve() {
  cin >> n;
  res = 0;
  bought = 0;
  for (int i = 0; i < n; i++) {
    cnt[i] = 0;
    V[i].clear();
  }
  for (int i = 1; i <= n; i++) {
    cin >> m[i] >> p[i];
    cnt[m[i]]++;
    V[m[i]].push_back(i);
  }
  for (int i = 1; i < n; i++) cnt[i] += cnt[i - 1];
  while (!H.empty()) H.pop();
  for (int j = n - 1; j >= 0; j--) {
    for (auto i : V[j]) H.push(p[i]);
    while (cnt[j - 1] + bought < j) {
      int p = H.top();
      H.pop();
      bought++;
      res += p;
    }
  }
  cout << res << '\n';
}
int main() {
  ios_base::sync_with_stdio(0);
  int t;
  cin >> t;
  for (int i = 1; i <= t; i++) solve();
  return 0;
}
