#include <bits/stdc++.h>
using namespace std;
vector<long long> a[5005];
int main() {
  int q;
  scanf("%d", &q);
  int n;
  int x;
  long long y;
  while (q--) {
    scanf("%d", &n);
    for (int i = 1; i <= n; i++) {
      scanf("%d%lld", &x, &y);
      a[x].push_back(y);
    }
    long long res = 0;
    for (int i = n - 1; i >= 0; i--) {
      sort(a[i].begin(), a[i].end());
      while (a[i].size() > n - i) {
        res = res + (*a[i].begin());
        a[i].erase(a[i].begin());
      }
    }
    printf("%lld\n", res);
  }
  return 0;
}
