#include <bits/stdc++.h>
using namespace std;
int main() {
  int n;
  cin >> n;
  for (int j = 0; j < n; j++) {
    int m;
    long long ans = 0;
    cin >> m;
    pair<long long, long long> ar[m + 5];
    for (int i = 0; i < m; i++) {
      cin >> ar[i].first >> ar[i].second;
      ans += ar[i].second;
    }
    sort(ar, ar + m);
    priority_queue<long long> pq;
    int pt = 1, pt2 = 0;
    bool flag = 0;
    while (pt < m) {
      if (pq.empty()) flag = 0;
      while (pt2 < m && ar[pt2].first <= pt) {
        if (ar[pt2].first == 0) flag = 1;
        pq.push(ar[pt2++].second);
      }
      if (!pq.empty()) {
        ans -= pq.top();
        pq.pop();
      }
      pt++;
    }
    if (!flag)
      cout << ans << endl;
    else
      cout << 0 << endl;
  }
}
