#include <bits/stdc++.h>
using namespace std;
const int tam = 100010;
const int MOD = 1e9 + 7;
const int MOD1 = 988244535;
const double EPS = 1e-9;
const double PI = acos(-1);
vector<pair<long long, int>> tips[200020];
pair<int, pair<long long, int>> ar[200020];
bool used[200020];
int main() {
  ios::sync_with_stdio(0);
  cin.tie(0);
  int cas;
  cin >> cas;
  long long res;
  while (cas--) {
    res = 0;
    int us = 0;
    int n;
    cin >> n;
    for (int i = 0; i < n; i++) used[i] = 0;
    for (int i = 0; i < n; i++) {
      cin >> ar[i].first >> ar[i].second.first;
      ar[i].second.second = i;
      tips[ar[i].first].push_back(make_pair(ar[i].second.first, i));
    }
    for (int i = 1; i < n + 1; i++) {
      sort((tips[i]).begin(), (tips[i]).end());
      for (int j = 0; n - tips[i].size() + j < i; j++) {
        res += tips[i][j].first;
        used[tips[i][j].second] = 1;
        us++;
      }
    }
    set<pair<long long, pair<int, int>>> st;
    for (int i = 0; i < n; i++) {
      if (!used[i])
        st.insert(make_pair(ar[i].second.first,
                            make_pair(ar[i].first, ar[i].second.second)));
    }
    sort(ar, ar + n);
    for (int i = 0; i < n; i++) {
      if (!used[ar[i].second.second]) {
        while (us < ar[i].first) {
          res += (*st.begin()).first;
          used[(*st.begin()).second.second] = 1;
          st.erase(st.begin());
          us++;
        }
        if (!used[ar[i].second.second]) {
          st.erase(make_pair(ar[i].second.first,
                             make_pair(ar[i].first, ar[i].second.second)));
          used[ar[i].second.second] = 1;
          us++;
        }
      }
    }
    cout << res << '\n';
    for (int i = 0; i < n; i++) tips[i].clear();
  }
  return 0;
}
