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