#include <bits/stdc++.h>
using namespace std;
void solve() {
  int N;
  cin >> N;
  vector<pair<int, int>> V(N);
  for (int i = 0; i < N; ++i) cin >> V[i].first >> V[i].second;
  sort(V.begin(), V.end());
  set<pair<int, int>> S;
  long long ans = 0;
  for (int i = N - 1; i >= 0; --i) {
    S.insert(make_pair(V[i].second, i));
    while (V[i].first > N - S.size()) {
      auto z = S.begin();
      ans += z->first;
      S.erase(z);
    }
  }
  cout << ans << endl;
}
int main() {
  ios_base::sync_with_stdio(false);
  cin.tie(NULL);
  int T;
  cin >> T;
  while (T--) solve();
  return 0;
}
