#include <bits/stdc++.h>
using namespace std;
void solve() {
  int n;
  cin >> n;
  vector<pair<int, int>> a(n);
  for (int i = 0; i < n; ++i) {
    cin >> a[i].first >> a[i].second;
  }
  sort(a.rbegin(), a.rend());
  multiset<int> s;
  long long ans = 0;
  int cnt = 0;
  for (int i = 0; i < n; ++i) {
    s.insert(a[i].second);
    if (n - i - 1 + cnt < a[i].first) {
      ans += *s.begin();
      s.erase(s.begin());
      ++cnt;
    }
  }
  cout << ans;
}
int main() {
  ios::sync_with_stdio(0);
  cin.tie(0), cout.tie(0);
  int t;
  cin >> t;
  while (t--) {
    solve();
    cout << '\n';
  }
  return 0;
}
