#include <bits/stdc++.h>
using namespace std;
vector<pair<long long, long long> > v;
bool f(long long val, long long n) {
  long long ac = 0;
  for (long long i = 0; i < n; i++) {
    if (v[i].first <= val) {
      ac++;
    } else {
      if (val > 0) {
        ac++;
        val--;
      } else {
        if (v[i].first <= ac) {
          ac++;
        }
      }
    }
  }
  return ac == n;
}
long long bb(long long l, long long r, long long n) {
  while (l != r) {
    long long med = (l + r) >> 1;
    if (!f(med, n)) {
      l = med + 1;
    } else {
      r = med;
    }
  }
  if (!f(l, n)) l++;
  return l;
}
bool cmp(pair<long long, long long> a, pair<long long, long long> b) {
  if (a.first == b.first) return a.second > b.second;
  return a.first < b.first;
}
void solve() {
  v.clear();
  long long n, cn, cost;
  cin >> n;
  for (long long i = 0; i < n; i++) {
    cin >> cn >> cost;
    v.push_back({cn, cost});
  }
  sort(v.begin(), v.end(), cmp);
  long long per = bb(0, n, n);
  vector<long long> rp;
  long long ans = 0;
  for (long long i = per; i < n; i++) {
    rp.push_back(v[i].second);
  }
  sort(rp.begin(), rp.end());
  for (long long i = 0; i < per; i++) {
    ans += rp[i];
  }
  cout << ans << "\n";
  return;
}
int main() {
  ios_base::sync_with_stdio(false);
  cin.tie(NULL);
  cout.tie(NULL);
  cout.precision(10);
  cout << fixed;
  long long t;
  cin >> t;
  while (t--) {
    solve();
  }
  return 0;
}
