#include <bits/stdc++.h>
using namespace std;
inline void fastio() {
  ios_base::sync_with_stdio(false);
  cin.tie(0);
  cout.tie(0);
}
void solve() {
  long long n;
  cin >> n;
  vector<vector<long long> > cnt(n);
  for (long long i = 0; i < n; ++i) {
    long long a, b;
    cin >> a >> b;
    cnt[a].push_back(b);
  }
  long long already = 0;
  long long ans = 0;
  multiset<long long> active;
  long long pref = n;
  for (long long i = n - 1; i >= 0; --i) {
    if (cnt[i].size() == 0) continue;
    pref -= cnt[i].size();
    for (auto j : cnt[i]) {
      active.insert(j);
    }
    if (pref + already < i) {
      long long na = already;
      for (long long j = 0; j < i - pref - already; ++j) {
        ans += *(active.begin());
        active.erase(active.begin());
        na++;
      }
      already = na;
    } else {
    }
  }
  cout << ans << '\n';
}
signed main() {
  fastio();
  long long T = 1;
  cin >> T;
  while (T--) {
    solve();
  }
  return 0;
}
