#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 <= (extra + curr_size) && added_next <= n) {
      curr_size += from[added_next].size();
      added_next++;
    }
    cnts[extra] = curr_size;
    if (prev_size == curr_size) {
      extra++;
    }
  }
  for (int j = extra; j <= n; j++) cnts[j] = n;
  long long best_sz = 10000000000000000LL;
  for (int k = 0; k <= n; k++) {
    if (cnts[k] == 0) continue;
    if (k < (n - cnts[k])) continue;
    multiset<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.find(*ss.rbegin()));
      }
      ss.insert(pp[j].second);
    }
    long long tmp = 0;
    int stop = k;
    for (auto x : ss) {
      if (stop == 0) break;
      tmp += x;
      stop--;
    }
    best_sz = min(best_sz, tmp);
    break;
  }
  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;
}
