#include <bits/stdc++.h>
using namespace std;
void solve() {
  int n;
  cin >> n;
  vector<pair<int, int>> pp(n);
  vector<vector<int>> from(n + 1);
  for (int i = 0; i < n; i++) {
    cin >> pp[i].first >> pp[i].second;
    from[pp[i].first].push_back(i);
  }
  sort(pp.begin(), pp.end());
  int extra = 0;
  int curr_size = 0;
  int added_next = 0;
  vector<int> cnts(n + 1);
  while (curr_size < n) {
    int prev_size = curr_size;
    while (added_next <= curr_size && added_next <= n) {
      curr_size += from[added_next].size();
      added_next++;
    }
    cnts[extra] = curr_size;
    if (prev_size == curr_size) {
      extra++;
      curr_size++;
    }
  }
  long long best_sz = 1000000000000LL;
  for (int k = 0; k <= n; k++) {
    if (cnts[k] == 0) continue;
    if (k < (n - cnts[k])) continue;
    set<pair<int, int>> ss;
    for (int j = 0; j < n; j++) {
      int set_size = j - (pp[j].first - k);
      while (ss.size() > 0 && ss.size() > set_size) {
        ss.erase(*ss.rbegin());
      }
      ss.insert({pp[j].second, j});
    }
    while (ss.size() > k) {
      ss.erase(*ss.rbegin());
    }
    if (ss.size() < k) continue;
    long long tmp = 0;
    for (auto x : ss) tmp += x.first;
    best_sz = min(best_sz, tmp);
  }
  cout << best_sz << "\n";
}
int main() {
  cin.tie(NULL);
  ios_base::sync_with_stdio(false);
  cout.tie(NULL);
  int t;
  cin >> t;
  while (t-- > 0) solve();
  return 0;
}
