#include <bits/stdc++.h>
#pragma GCC optimize("Ofast")
using namespace std;
const long long N = 2e6;
int32_t main() {
  ios_base::sync_with_stdio(0);
  cin.tie(0);
  cout.tie(0);
  long long qq;
  cin >> qq;
  while (qq--) {
    long long n;
    cin >> n;
    long long p[n + 1], m[n + 1], cnt[n + 10];
    fill(cnt, cnt + n + 2, 0);
    vector<pair<long long, long long> > vec;
    for (long long i = 0; i < n; i++) {
      cin >> m[i] >> p[i];
      vec.push_back({m[i], p[i]});
      cnt[m[i]]++;
    }
    sort(vec.rbegin(), vec.rend());
    long long pref = n;
    long long uk = 0;
    long long ans = 0;
    long long cur = 0;
    priority_queue<long long> q;
    for (long long i = n; i >= 0; i--) {
      pref -= cnt[i];
      long long need = max(0ll, i - pref - uk);
      while (cur < n && vec[cur].first >= i) q.push(-vec[cur].second), cur++;
      while (need > 0 && !q.empty()) ans -= q.top(), q.pop(), uk++, need--;
    }
    cout << ans << endl;
  }
  return 0;
}
