#include <bits/stdc++.h>
using namespace std;
int main() {
  ios_base::sync_with_stdio(false);
  cin.tie(NULL);
  cout.tie(NULL);
  long long t;
  cin >> t;
  while (t--) {
    long long n;
    cin >> n;
    vector<pair<long long, long long> > arr(n);
    for (int i = 0; i < n; i++) cin >> arr[i].first >> arr[i].second;
    multiset<long long> s;
    sort(arr.begin(), arr.end());
    long long cnt = 0, sum = 0;
    for (int i = n - 1; i >= 0; i--) {
      long long m = arr[i].first;
      s.insert(arr[i].second);
      if (m > cnt + (i)) {
        multiset<long long>::iterator it = s.begin();
        cnt++;
        sum += (*it);
        s.erase(it);
      }
    }
    cout << sum << "\n";
  }
}
