#include <bits/stdc++.h>
using namespace std;
map<long long, vector<long long>> m;
multiset<long long> s;
void solve() {
  long long i, n, ans = 0, a, b, cnt = 0, cnt1 = 0, uk, mn = 1e15;
  s.clear();
  m.clear();
  cin >> n;
  for (i = 0; i < n; i++) {
    cin >> a >> b;
    m[-a].push_back(b);
  }
  for (auto &it : m) {
    sort(it.second.begin(), it.second.end());
    uk = 0;
    cnt += it.second.size();
    for (uk = 0; uk < it.second.size(); uk++) s.insert(it.second[uk]);
    uk = 0;
    while (n - cnt + cnt1 < -it.first) {
      ans += *s.begin();
      s.erase(s.begin());
      cnt1++;
    }
    mn = min(mn, -it.first);
  }
  while (cnt1 < mn) {
    ans += *s.begin();
    s.erase(s.begin());
    cnt1++;
  }
  cout << ans << '\n';
}
int main() {
  ios_base::sync_with_stdio(false);
  cin.tie(NULL);
  int i, n;
  cin >> n;
  for (i = 0; i < n; i++) solve();
  return 0;
}
