#include <bits/stdc++.h>
using namespace std;
using LL = long long;
using PII = pair<int, int>;
void solve() {
  int n;
  scanf("%d", &n);
  vector<pair<int, int>> a(n);
  LL suf = 0, ans = 0;
  for (int i = 0; i < n; ++i)
    scanf("%d%d", &a[i].first, &a[i].second), ans += a[i].second;
  sort(a.begin(), a.end(), [](PII x, PII y) {
    return make_pair(x.first, -x.second) < make_pair(y.first, -y.second);
  });
  for (int i = n - 1; i >= 0; --i) {
    int need = 0, cnt = n - 1 - i;
    multiset<int> se;
    for (int j = 0; j <= i; ++j) {
      se.insert(a[j].second);
      if ((j == 0 || a[j].first != a[j - 1].first) && cnt + j < a[j].first)
        need += a[j].first - cnt - j;
    }
    LL sum = suf;
    if (need <= (int)se.size()) {
      for (int x : se) {
        if (!need) break;
        sum += x, --need;
      }
      ans = min(ans, sum);
    }
    suf += a[i].second;
  }
  printf("%lld\n", ans);
}
int main() {
  int t;
  cin >> t;
  while (t--) solve();
}
