#include <bits/stdc++.h>
typedef struct __st_pair {
  int m, p;
} pair;
pair arr[200005];
long long ans[2][5003];
int n;
int cmp_fn(const void *_a, const void *_b) {
  pair *a, *b;
  a = (pair *)_a;
  b = (pair *)_b;
  return (a->m) - (b->m);
}
int main() {
  int tcases;
  scanf("%d", &tcases);
  while (tcases--) {
    int i, cur;
    scanf("%d", &n);
    for (i = 0; i < n; i++) scanf("%d %d", &(arr[i].m), &(arr[i].p));
    qsort(arr, n, sizeof(pair), cmp_fn);
    cur = 0;
    for (i = 0; i <= n; i++) ans[cur][i] = 0;
    for (i = 0; i < n; i++) {
      int old, j;
      old = cur;
      cur ^= 1;
      for (j = 0; j < n; j++) ans[cur][j] = ans[old][j + 1] + arr[i].p;
      ans[cur][n] = 0;
      int req = arr[i].m - i;
      if (req < 0) req = 0;
      for (j = req; j <= n; j++)
        if (ans[cur][j] > ans[old][j]) ans[cur][j] = ans[old][j];
      if (0) {
        printf("---\n");
        for (j = 0; j <= n; j++)
          printf("%d:\t%lld\t%lld\n", j, ans[old][j], ans[cur][j]);
        printf("---\n");
      }
    }
    printf("%lld\n", ans[cur][0]);
  }
  return 0;
}
