#include <bits/stdc++.h>
using namespace std;
const int maxn = 5e3 + 5;
int n, m, p;
vector<int> f[maxn];
int main() {
  int T;
  cin >> T;
  while (T--) {
    scanf("%d", &n);
    int i, j, k;
    for (i = 0; i <= n; i++) f[i].clear();
    for (i = 1; i <= n; i++) {
      scanf("%d%d", &m, &p);
      f[m].push_back(p);
    }
    priority_queue<int, vector<int>, greater<int> > q;
    long long ans = 0;
    for (i = n - 1; i >= 0; i--) {
      k = f[i].size();
      for (j = 0; j < k; j++) q.push(f[i][j]);
      while (q.size() > n - i) {
        p = q.top();
        ans += p;
        q.pop();
      }
    }
    printf("%lld\n", ans);
  }
  return 0;
}
