#include <bits/stdc++.h>
const int MAXN = 30100;
class Vote {
 public:
  int p, m;
  friend bool operator<(const Vote &v1, const Vote &v2) { return v1.m < v2.m; }
} v[MAXN];
bool vis[MAXN];
int main() {
  int t, n;
  scanf("%d", &t);
  while (t--) {
    scanf("%d", &n);
    for (int i = 0; i < n; ++i) scanf("%d%d", &v[i].m, &v[i].p);
    std::sort(v, v + n);
    for (int i = 0; i < n; ++i) vis[i] = false;
    long long ans = 0;
    int cnt = 0;
    while (cnt < n) {
      int idx = n - 1, pp = 1000000007, sel;
      for (; idx >= 0; --idx) {
        if (vis[idx]) continue;
        if (cnt + idx < v[idx].m) break;
        if (v[idx].p < pp) {
          pp = v[idx].p;
          sel = idx;
        }
      }
      if (idx < 0) break;
      ans += v[sel].p;
      vis[sel] = true;
      ++cnt;
    }
    printf("%lld\n", ans);
  }
  return 0;
}
