#include <bits/stdc++.h>
using namespace std;
class myComparator {
 public:
  bool operator()(pair<long long, long long> a, pair<long long, long long> b) {
    if (a.second == b.second) {
      return (a.first < b.first);
    }
    return (a.second < b.second);
  }
};
int main(int argc, char** argv) {
  ios_base::sync_with_stdio(false);
  cin.tie(NULL);
  long long t;
  cin >> t;
  while (t--) {
    long long n;
    cin >> n;
    vector<pair<long long, long long> > voters(n, {0, 0});
    for (long long i = 0; i < n; ++i) {
      long long a, b;
      cin >> a >> b;
      voters[i] = {a, b};
    }
    sort(voters.begin(), voters.end());
    reverse(voters.begin(), voters.end());
    long long totalvotes = 0;
    long long totalcost = 0;
    multiset<pair<long long, long long>, myComparator> myset;
    for (long long i = 0; i < n; ++i) {
      myset.insert(voters[i]);
      long long requiredvotes = voters[i].first - totalvotes;
      while (requiredvotes > n - i - 1 && !myset.empty() &&
             myset.find(voters[i]) != myset.end()) {
        pair<long long, long long> cheapest = *myset.begin();
        totalcost += cheapest.second;
        totalvotes++;
        myset.erase(cheapest);
        requiredvotes = voters[i].first - totalvotes;
      }
    }
    cout << totalcost << '\n';
  }
  return 0;
}
