#include <bits/stdc++.h>
using namespace std;
int main() {
  ios_base::sync_with_stdio(false);
  cin.tie(NULL);
  ;
  long long t;
  cin >> t;
  while (t--) {
    long long n;
    cin >> n;
    vector<pair<int, int> > v;
    for (long long i = 0; i < n; i++) {
      long long a, b;
      cin >> a >> b;
      v.push_back({a, b});
    }
    sort(v.begin(), v.end());
    long long ans = 0, cnt = 0;
    multiset<long long> pq;
    for (long long i = n - 1; i >= 0; i--) {
      pq.insert(v[i].second);
      if (i + cnt < v[i].first) {
        ans += *pq.begin();
        pq.erase(pq.begin());
        cnt++;
      }
    }
    cout << ans << '\n';
  }
  return 0;
}
