#include <bits/stdc++.h>
using namespace std;
void solve() {
  long long n;
  cin >> n;
  vector<vector<long long>> cnt(n);
  for (long long i = 0; i < n; i++) {
    long long m, p;
    cin >> m >> p;
    cnt[m].push_back(p);
  }
  long long cur = n, vz = 0, ans = 0;
  multiset<long long> av;
  for (long long i = n - 1; i >= 0; i--)
    if (cnt[i].size()) {
      cur -= cnt[i].size();
      for (auto&& v : cnt[i]) av.insert(v);
      while (cur + vz < i) vz++, ans += (*av.begin()), av.erase(av.begin());
    }
  cout << ans << endl;
}
int main() {
  long long t;
  cin >> t;
  for (long long i = 0; i < t; i++) solve();
}
