#include <bits/stdc++.h>
using namespace std;
int main() {
  ios_base::sync_with_stdio(0);
  cin.tie(0);
  int t;
  cin >> t;
  while (t--) {
    int n;
    cin >> n;
    vector<pair<int, int> > a(n);
    for (pair<int, int>& ai : a) cin >> ai.first >> ai.second;
    sort((a).begin(), (a).end());
    long long r = 0;
    int i = n - 1, s = 0;
    priority_queue<int> m;
    while (i >= 0) {
      int j = i;
      while (j >= 0 && a[j].first == a[i].first) m.push(-a[j--].second);
      while (s + j + 1 < a[i].first) {
        r += -m.top();
        m.pop();
        ++s;
      }
      i = j;
    }
    cout << r << "\n";
  }
  return 0;
}
