#include <bits/stdc++.h>
using namespace std;
const int maxn = 5010;
inline int read() {
  int x = 0, t = 1;
  char c = getchar();
  while (c < '0' || c > '9') {
    if (c == '-') t = -1;
    c = getchar();
  }
  while (c >= '0' && c <= '9') {
    x = x * 10 + c - '0';
    c = getchar();
  }
  return x * t;
}
vector<int> e[maxn];
int main() {
  int t;
  t = read();
  while (t--) {
    int n;
    n = read();
    for (register int i = 0; i < n; ++i) e[i].clear();
    for (register int i = 1; i <= n; ++i) {
      int m, p;
      m = read(), p = read();
      e[m].push_back(p);
    }
    priority_queue<int, vector<int>, greater<int> > q;
    long long ans = 0;
    for (register int i = n - 1; i >= 0; --i) {
      int len = e[i].size();
      for (register int j = 0; j < len; ++j) q.push(e[i][j]);
      while (q.size() > n - i) {
        ans += q.top();
        q.pop();
      }
    }
    printf("%lld\n", ans);
  }
  return 0;
}
