#include <bits/stdc++.h>
using namespace std;
long long int buyCheapest(vector<pair<long long int, long long int> >& v,
                          long long int m, long long int rem) {
  long long int ans = 0;
  for (long long int i = (long long int)0;
       i < (long long int)(long long int)(v.size()); i++) {
    if (v[i].second < m && rem > 0) {
      rem--;
      ans += v[i].first;
    }
  }
  return ans;
}
int main() {
  ios_base::sync_with_stdio(false);
  cin.tie(NULL);
  long long int t;
  cin >> t;
  while (t--) {
    long long int n;
    cin >> n;
    vector<pair<long long int, long long int> > v(n), w(n);
    for (long long int i = (long long int)0; i < (long long int)n; i++) {
      cin >> v[i].second >> v[i].first;
      w[i] = v[i];
      swap(w[i].first, w[i].second);
    }
    sort(v.begin(), v.end());
    sort(w.rbegin(), w.rend());
    long long int paid = 0;
    long long int ans = 2000000000000000000LL;
    long long int i = 0;
    for (long long int k = (long long int)n + 1 - 1LL; k >= (long long int)0;
         k--) {
      while (i < n && w[i].first >= k) {
        paid += w[i].second;
        i++;
      }
      i--;
      long long int total = paid + buyCheapest(v, k, k - (i + 1));
      ans = min(ans, total);
    }
    cout << ans << endl;
  }
  return 0;
}
