#include <bits/stdc++.h>
using namespace std;
const int maxn = 5e3 + 5;
int T, num[maxn], n;
struct node {
  int m, p;
  bool operator<(const node &g) const { return p < g.p; }
} a[maxn];
int ub[maxn], mx[maxn << 2], lazy[maxn << 2];
void build(int k, int lef, int rig) {
  lazy[k] = 0;
  if (lef == rig) {
    mx[k] = ub[lef];
    return;
  }
  int mid = (lef + rig) >> 1;
  build(k << 1, lef, mid);
  build(k << 1 | 1, mid + 1, rig);
  mx[k] = min(mx[k << 1], mx[k << 1 | 1]);
}
void pushDown(int k) {
  if (lazy[k]) {
    int c = lazy[k];
    mx[k << 1] += c;
    mx[k << 1 | 1] += c;
    lazy[k << 1] += c;
    lazy[k << 1 | 1] += c;
    lazy[k] = 0;
  }
}
void update(int k, int lef, int rig, int l, int r, int c) {
  if (l <= lef && r >= rig) {
    mx[k] += c;
    lazy[k] += c;
    return;
  }
  int mid = (lef + rig) >> 1;
  pushDown(k);
  if (l <= mid) update(k << 1, lef, mid, l, r, c);
  if (r > mid) update(k << 1 | 1, mid + 1, rig, l, r, c);
  mx[k] = min(mx[k << 1], mx[k << 1 | 1]);
}
int query(int k, int lef, int rig, int l, int r) {
  if (l <= lef && r >= rig) return mx[k];
  int mid = (lef + rig) >> 1;
  pushDown(k);
  int ans = n;
  if (l <= mid) ans = min(ans, query(k << 1, lef, mid, l, r));
  if (r > mid) ans = min(ans, query(k << 1 | 1, mid + 1, rig, l, r));
  return ans;
}
int t[maxn];
int main() {
  scanf("%d", &T);
  while (T--) {
    scanf("%d", &n);
    for (int i = 0; i <= n; i++) num[i] = 0, t[i] = 0;
    for (int i = 1; i <= n; i++) scanf("%d%d", &a[i].m, &a[i].p), num[a[i].m]++;
    sort(a + 1, a + n + 1);
    for (int i = 1; i <= n; i++) num[i] += num[i - 1];
    long long ans = 1e16;
    for (int i = 0; i <= n; i++) {
      for (int j = 0; j <= n - 1; j++) ub[j] = i + num[j] - j - 1;
      build(1, 0, n - 1);
      long long res = 0;
      int cnt = 0;
      if (mx[1] < 0) continue;
      for (int j = 1; j <= n; j++) {
        int id = a[j].m;
        if (cnt == i) break;
        if (t[id] < num[id] - (id ? num[id - 1] : 0) &&
            query(1, 0, n - 1, id, n - 1) > 0) {
          cnt++;
          t[id]++;
          update(1, 0, n - 1, id, n - 1, -1);
          res += a[j].p;
        }
      }
      if (cnt == i) ans = min(ans, res);
    }
    printf("%lld\n", ans);
  }
  return 0;
}
