#include <bits/stdc++.h>
using namespace std;
int main() {
  int n, t;
  cin >> t;
  while (t--) {
    long long ans = 0;
    scanf("%d", &n);
    multiset<pair<int, int> > s1, s2, paid;
    multiset<int> s;
    pair<int, int> tmp;
    int num_paid = 0, p, m, num_votes = 0;
    for (int i = 0; i < n; ++i) {
      scanf("%d%d", &m, &p);
      s1.insert(make_pair(p, m));
      s2.insert(make_pair(m, p));
    }
    while (s2.size() > 0) {
      tmp = *s2.begin();
      if (tmp.first <= num_votes) {
        while (s2.size() > 0) {
          tmp = *s2.begin();
          if (tmp.first > num_votes) break;
          s2.erase(s2.begin());
          s1.erase(s1.find(make_pair(tmp.second, tmp.first)));
          ++num_votes;
        }
        continue;
      }
      tmp = *s1.begin();
      s1.erase(s1.begin());
      s2.erase(make_pair(tmp.second, tmp.first));
      paid.insert(make_pair(tmp.second, tmp.first));
      ++num_votes;
      ans += tmp.first;
      while (paid.size()) {
        if ((paid.begin()->first) < num_votes) {
          s.insert(-(*paid.begin()).second);
          paid.erase(paid.begin());
        } else {
          break;
        }
      }
      if (s.size()) {
        ans += *s.begin();
        s.erase(s.begin());
      }
    }
    printf("%lld\n", ans);
  }
  return 0;
}
