#include <bits/stdc++.h>
const double pi = acos(-1.0);
const int maxn = (1000 + 10);
const int inf = 0x3f3f3f3f;
const long long mod = 10000003;
using namespace std;
long long in() {
  long long x = 0, f = 0;
  char ch = getchar();
  while (ch < '0' || ch > '9') f |= ch == '-', ch = getchar();
  while (ch >= '0' && ch <= '9') x = x * 10 + ch - '0', ch = getchar();
  return f ? -x : x;
}
struct node {
  long long val;
  friend bool operator<(node a, node b) { return a.val > b.val; }
};
vector<long long> e[5001];
vector<long long>::iterator it;
priority_queue<node> val;
int main() {
  ios::sync_with_stdio(false);
  long long t, n;
  cin >> t;
  while (t--) {
    cin >> n;
    long long ans = 0;
    while (!val.empty()) val.pop();
    for (long long i = 1; i <= 5000; i++) e[i].clear();
    for (long long i = 1; i <= n; i++) {
      long long m, p;
      cin >> m >> p;
      node a;
      a.val = p;
      e[m].push_back(p);
    }
    for (long long i = n - 1; i >= 0; i--) {
      if (e[i].size() != 0) {
        for (it = e[i].begin(); it != e[i].end(); it++) {
          node a;
          a.val = *it;
          val.push(a);
        }
        while (n - val.size() < i) {
          ans += val.top().val;
          val.pop();
        }
      }
    }
    cout << ans << endl;
  }
  return 0;
}
