#include <bits/stdc++.h>
using namespace std;
struct node {
  int p, m;
} q[5010];
int tmp(node s1, node s2) {
  if (s1.p == s2.p) return s1.m < s2.m;
  return s1.p < s2.p;
}
int tmp1(node s1, node s2) { return s1.m < s2.m; }
int lv[5010];
int main() {
  int t;
  scanf("%d", &t);
  while (t--) {
    long long n;
    scanf("%lld", &n);
    for (int i = 1; i <= n; i++) scanf("%lld%lld", &q[i].p, &q[i].m);
    long long sum = 0;
    sort(q + 1, q + 1 + n, tmp);
    for (int i = 1; i <= n; i++) {
      lv[i] = max(0, q[i].p - i + 1);
    }
    long long ans = 0;
    for (int i = n; i >= 1; i--) {
      lv[i] = max(lv[i] - sum, 0ll);
      if (lv[i]) {
        sort(q + i, q + n + 1, tmp1);
        for (int j = i; j < i + lv[i]; j++) {
          ans += q[j].m;
          q[j].m = 0x3f3f3f3f;
          sum++;
        }
      }
    }
    cout << ans << endl;
  }
}
