#include <bits/stdc++.h>
using namespace std;
bool compare(int a, int b) { return a > b; }
int main() {
  ios_base::sync_with_stdio(false);
  cin.tie(0);
  cout.tie(0);
  int t;
  cin >> t;
  while (t--) {
    int n;
    cin >> n;
    unordered_map<int, vector<long long int> > mp;
    map<int, int> mp1;
    long long int m, p;
    long long int ans = 0;
    long long int count = 0;
    for (int i = 0; i < n; i++) {
      cin >> m >> p;
      if (!m)
        count++;
      else
        mp[m].push_back(p);
    }
    for (auto it = mp.begin(); it != mp.end(); it++) {
      vector<long long int> &temp = it->second;
      sort(temp.begin(), temp.end(), compare);
      while (n - temp.size() < it->first) {
        ans += temp[temp.size() - 1];
        count++;
        temp.pop_back();
      }
      if (temp.size()) mp1[it->first] = temp.size();
    }
    vector<pair<long long int, int> > v;
    for (auto it = mp.begin(); it != mp.end(); it++) {
      vector<long long int> temp = it->second;
      for (int i = 0; i < temp.size(); i++)
        v.push_back(make_pair(temp[i], it->first));
    }
    sort(v.begin(), v.end());
    auto it = mp1.begin();
    int i = 0;
    while (it != mp1.end()) {
      int c0 = 0;
      while (count + c0 < it->first) {
        if (v[i].second < it->first) {
          i++;
          continue;
        }
        ans += v[i].first;
        if (v[i].second == it->first)
          c0++;
        else {
          count++;
          mp1[v[i].second]--;
        }
        i++;
      }
      count += it->second;
      it++;
    }
    cout << ans << endl;
  }
  return 0;
}
