#include <bits/stdc++.h>
using namespace std;
int main() {
  ios::sync_with_stdio(false);
  cin.tie(0);
  cout.tie(NULL);
  ;
  int t;
  cin >> t;
  while (t--) {
    int n;
    cin >> n;
    vector<pair<long long int, long long int>> ar;
    for (int i = 0; i < n; i++) {
      long long int x, y;
      cin >> x >> y;
      ar.push_back({x, y});
    }
    sort(ar.begin(), ar.end());
    priority_queue<long long int, vector<long long int>, greater<long long int>>
        p;
    long long int sum = 0, cnt = 0;
    for (long long int i = n - 1; i >= 0; i--) {
      p.push(ar[i].second);
      if (i + cnt >= ar[i].first) continue;
      cnt++;
      sum += p.top();
      p.pop();
    }
    cout << sum << "\n";
  }
}
